Cesar Cotiz Cesar Cotiz - 10 months ago 38
Python Question

How can I validate my forms or views in Django so that they can only edit the User Model only to those that belong to that data?

I have 2 models that I will allow users to edit separately, one is called User(Django default auth) and the other is UserProfile.

models.py (UserProfile)

class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='avatar', default='avatar/default.png')
header = models.ImageField(upload_to='header', default='header/default.png')
bio = models.TextField(max_length=140, blank=True)
website = models.URLField(max_length=200, blank=True)
location = models.CharField(max_length=30, blank=True)
date_birth = models.DateField(null=True, blank=True)


class UserUpdateView(generic.UpdateView):
This view is for editing only the User model. /edit/
model = User
slug_field = 'username'
form_class = UserForm
template_name = 'user/user_edit.html'

Answer Source

First, use the LoginRequiredMixin mixin so that only logged-in users can access the view.

Then, override the get_object method, and return the model instance you want to edit.

You don't need the username in the URL any more, so you can remove slug_field = 'username'.

from django.contrib.auth.mixins import LoginRequiredMixin

class UserUpdateView(LoginRequiredMixin, generic.UpdateView):
    model = User
    form_class = UserForm
    template_name = 'user/user_edit.html'

    def get_object(self):
        return self.request.user

If you have a similar view for editing the user profile you would return self.request.user.userprofile instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download