Goun2 Goun2 - 12 days ago 7
Python Question

Error Generic detail view must be called with either an object pk or a slug, even with the pk

i'm trying to update records of a view which has a foreign key field, due to this i'm getting an error, since i tried to update another model without a foreign key field and it worked very well.

There are other quetions like this, but in my case i'm passing the pk.

urls.py

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

]


views.py

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

def get_success_url(self):
return reverse("courses")


updatestudent.html

<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update" />
</form>


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


error

AttributeError: Generic detail view updatestudent must be called with either an object pk or a slug.

Answer

Django doesn't expect you to use studentpk in the URL pattern. The easiest fix is to use pk instead.

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

If you really want to use studentpk, then set pk_url_kwarg in the view.

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

    pk_url_kwarg = 'studentpk'

Note that in Python, the recommended style is to name your class based view UpdateStudent, and your form class StudentForm.

Comments