user2896120
user2896120

Reputation: 3282

TypeError: post() got an unexpected keyword argument 'slug'

I have a DetailView that displays a user's profile page. The profile takes a slug name that is part of the URL. For example, /profile/john/ where john is the username, and we are on john's profile. As shown here:

class ProfileView(DetailView):
    model = User
    slug_field = 'username'
    template_name = 'oauth/profile.html'
    context_object_name = 'user_profile' 

    def post(self, request):
        return render(request, self.template_name)

Now whenever I submit a form, I get an error that says: TypeError: post() got an unexpected keyword argument 'slug' Knowing this, I added a new argument in the post method which is slug. However, when I submit the form, I get a blank page with no details about the user. We get redirected to the same page, but this time with no values about the user profile. What am I doing wrong?

Upvotes: 3

Views: 4530

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

You should add slug as method argument also:

def post(self, request, slug):
    return render(request, self.template_name)

You need to pass context to the template as well:

def post(self, request, slug):
    self.object = self.get_object()
    context = self.get_context_data(object=self.object)
    return render(request, self.template_name, context=context)

But actually since your post doesn't add specific logic to the view you can just call super:

def post(self, request, slug):
    return super().post(request, slug)

Or simply remove post method completely cause it's redundant.

Upvotes: 5

Related Questions