I keep getting a reverse error when i try to redirect from a DetailView and CreateView. I keep getting object has no attribute pk. I have equally tried using : args=[str(self.id)]) but i still get the error.
class check (DetailView)
def get(self, request, *args, **kwargs):
if...:
return reverse('no_edit', kwargs={"pk": self.pk})
self
is the DetailView
object, which indeed has no primary key. If you want to access the object, you normally can use self.object
, but since you have overwritten the get
method itself, that will not work either.
You can fix it by calling self.get_object()
here, like:
from django.shortcuts import redirect
class CheckView(DetailView):
# …
def get(self, request, *args, **kwargs):
self.object = self.get_object()
if …:
return redirect('no_edit', pk=self.object.pk)
We can here make use of redirect(..)
[Django-doc]. This will construct a HttpResponseRedirect
with the result of a reverse
call.