错误通用详细信息视图必须使用对象pk或slug调用,即使使用pk也是如此

Gou*_*un2 1 python django django-views django-class-based-views

我正在尝试更新具有外键字段的视图的记录,因为我遇到了错误,因为我尝试更新没有外键字段的另一个模型并且它工作得非常好.

还有其他这样的排队,但在我的情况下,我正在通过PK.

urls.py

 urlpatterns = [
        url(r'^info/(?P<studentpk>\d+)/update/$', views.updatestudent.as_view(), name="updatestudent"),

]
Run Code Online (Sandbox Code Playgroud)

views.py

class updatestudent(UpdateView):
    model = Student
    form_class = forms.studentform
    template_name = "temp/updatestudent.html"

    def get_success_url(self):
        return reverse("courses")
Run Code Online (Sandbox Code Playgroud)

updatestudent.html

<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Update" />
</form>
Run Code Online (Sandbox Code Playgroud)

models.py

class Student(models.Model):
    classfk = models.ForeignKey(Class)
    name = models.CharField(max_length=100)
    birth_date = models.DateField('Birthdate')

    def __str__(self):
        return self.name
Run Code Online (Sandbox Code Playgroud)

错误

AttributeError: Generic detail view updatestudent must be called with either an object pk or a slug.
Run Code Online (Sandbox Code Playgroud)

Ala*_*air 7

Django不希望你studentpk在URL模式中使用.最简单的解决方法是使用pk.

url(r'^info/(?P<pk>\d+)/update/$', views.updatestudent.as_view(), name="updatestudent"),
Run Code Online (Sandbox Code Playgroud)

如果您确实想使用studentpk,请pk_url_kwarg在视图中进行设置.

class updatestudent(UpdateView):
    model = Student
    form_class = forms.studentform
    template_name = "temp/updatestudent.html"

    pk_url_kwarg = 'studentpk'
Run Code Online (Sandbox Code Playgroud)

请注意,在Python中,建议的样式是命名基于类的视图UpdateStudent和表单类StudentForm.