django2: url 基于 pk 不工作

django2: url based on pk not working

我想要模型 ImpCalendar 的表单(网页),以便我可以编辑它的数据。 url 应该有 calendar_id (主键),我在 urls.py

中设置了它

模型 (ImpCalendar) 有指向 Establishments 的外键。我没有在 view/form 中使用那个外键,所以我不知道它是否相关。

如果我在 views.py;

return render(request, 'importer/calendaredit.html', {'form': calendar})

我确实在页面上看到了数据,但没有看到(编辑)表单。只是数据,不是填写字段。

当我做的时候

return render(request, 'importer/calendaredit.html', {'form': form})

这对我来说听起来合乎逻辑,但我得到了错误

django.urls.exceptions.NoReverseMatch: Reverse for 'calendaredit' with arguments '('',)' not found. 1 pattern(s) tried: ['importer\/calendar\/(?P<calendar_id>[0-9]+)\/$']

在我看来,calendar_id 返回的值现在是表单数据 (html),它无法对其进行任何操作。但我不知道我做错了什么。它必须对 html 代码和传输给它的值做一些事情,但我是最后一个。

models.py

class Impcalendar(models.Model):
    establishment = models.ForeignKey(Establishments, on_delete=SET_NULL, null=True)
    url = models.CharField(max_length=255)
    comment = models.CharField(max_length=255, null=True, blank=True)
    status = models.IntegerField(null=True, blank=True)
    def __str__(self):
        return str(self.establishment)

forms.py

from django import forms
import datetime
from importer.models import Impcalendar, Establishments

class ImpcalendarForm(forms.ModelForm):
        class Meta:
            model = Impcalendar
            fields = ['id', 'url']

urls.py

from django.urls import path
from importer import views

urlpatterns = [
    path('', views.index, name='index'),
    path('calendar/<int:calendar_id>/', views.calendaredit,    name='calendaredit')
]

views.py

def calendaredit(request, calendar_id):
    calendar = get_object_or_404(Impcalendar, pk=calendar_id)

    print (calendar.url)
    if request.method == 'POST':
        form = ImpcalendarForm(request.POST, instance=calendar)
        if form.is_valid():
            calendar.save()
    else:
        form = ImpcalendarForm(request.POST or None,  instance=calendar)
    return render(request, 'importer/calendaredit.html', {'form': form})

calendaredit.html

{% extends 'importer/base.html' %}
{% block content %}
<h1>{{ form.id }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'calendaredit' form.id %}" method="post">
   <div class="fieldWrapper">
      {% csrf_token %}
      {{ form.id }}
      {{ form.url }}
   </div>
<input type="submit" value="Save" />
</form>

{% endblock %}

你需要传递两个东西,称呼它们是什么,并参考日历而不是表格。

return render(request, 'importer/calendaredit.html', {'form': form, 'calendar': calendar})

...

<form action="{% url 'calendaredit' calendar.id %}" method="post">