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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With