Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating User model in Django with class based UpdateView

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())
like image 713
thesteve Avatar asked May 30 '11 21:05

thesteve


2 Answers

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
like image 88
thesteve Avatar answered Nov 12 '22 02:11

thesteve


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.

like image 24
Baz Avatar answered Nov 12 '22 01:11

Baz