Home > Software design >  Django Class Based View - Generic detail View must be called with object pk or a slug in URLconf
Django Class Based View - Generic detail View must be called with object pk or a slug in URLconf

Time:11-30

So I have a program that takes in the currently logged in user and updates their profile image. Initially I had a function based view, and a url matching pattern (the url for accessing profile, and thereby editing it is localhost:8000/profile)

#views.py
@login_required
def profile(request):
  if request.method=="POST":
      u_form=UserUpdateForm(request.POST, instance=request.user)
      p_form=ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
      if u_form.is_valid() and p_form.is_valid():
          u_form.save()
          p_form.save()
          messages.success(request, "Your account has been updated!")
          return redirect('profile')
  else:
      u_form=UserUpdateForm(instance=request.user)
      p_form=ProfileUpdateForm(instance=request.user.profile)


  context={'u_form':u_form, 'p_form':p_form}
  return render(request, 'users/profile.html', context)

#following line in URLpatterns of urls.py 
path('profile/', user_views.ProfileUpdateView.as_view(), name='profile'),

It worked fine. However when I tried changing it to a class based view as below, it started giving errors

#views.py
class ProfileUpdateView(UpdateView):
    model=Profile
    fields=['image']

Case 1: I had this in urls.py URLpatterns

  path('profile/', user_views.ProfileUpdateView.as_view(), name='profile'),

It gave an error -

(https://i.stack.imgur.com/6mXfI.png)](https://i.stack.imgur.com/6mXfI.png) I don't understand why this error popped up because there is no page specific ID, like profile/1, profile/2 - just profile/ because the user is automatically identified by who is currently logged in hence no need to pass in a separate parameter in the url

Case 2: after I added in pk parameter

path('profile/<int:pk>/', user_views.ProfileUpdateView.as_view(), name='profile'),

This error pops up (https://i.stack.imgur.com/Op9eQ.png)](https://i.stack.imgur.com/Op9eQ.png)

I have been stuck for a day now. I went through the Django documentation and MDN docs as well. Still can't figure out

CodePudding user response:

As far as I can understand, the Profile is a model linked with the user. If Profile is in OneToOneField with User, then in your class based view, ovverride the get_object method as:

def get_object(queryset=None,**kwargs):
    return self.request.user.profile

If your Profile is linked with ForeignKey to User, then your get_object method will change to:

def get_object(queryset=None,**kwargs):
    return Profile.objects.get(user=self.request.user)

CodePudding user response:

In your class override get_object method as:

def get_object(self, **kwargs):
    return Profile.objects.get(id=kwargs["int"])
  • Related