开发者

Updating User model in Django with class based UpdateView

开发者 https://www.devze.com 2023-03-09 20:23 出处:网络
I am trying to update the Django User model with the class based UpdateView that automatically renders with the current user but am getting an error that a pk or slug is required. The form work and re

I am trying to update the Django User model with the class based UpdateView that automatically renders with the current user but am getting an error that a pk or slug is required. The form work and renders with the proper current user context but throws the error when I try to submit the changes. Below is the view I am using:

class UserUpdateView(UpdateView):
    form_class = UserForm
    model = User
    template_name = 'members/user_update.html'

    def get(self, request, **kwargs):
        self.object = User.objects.get(username=self.request.user)
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        context = self.get_context_data(开发者_如何学编程object=self.object, form=form)
        return self.render_to_response(context)

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())


I need to override the get_object() method on the update view and do not need to override form_valid. The custom get_object() method is:

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


I know this is an old post but something stood out to me and this comment is info for newcomers.

The get call for self.object will work but it's not matching the actual fields to get username as it's supplying the user instance:

self.object = User.objects.get(username=self.request.user)

You should match the username argument with the instance username argument:

self.object = User.objects.get(username=self.request.user.username)

Better still, use the pk (id):

self.object = User.objects.get(pk=self.request.user.pk)

There could be a neater way of doing this, so I'm open to suggestions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号