0

I am working on a problem where I need to update some fields of user model with one field of the model in which it is inherited. Using updateview with that model shows errors. How am I supposed to do it? thanks in advance.

models.py

 class UserProfile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True)
    role = models.CharField(max_length=50, choices=Roles)
    verified =models.BooleanField(default = False,blank=True)
    photo = models.ImageField(upload_to='images', blank=True, default='default/testimonial2.jpg')

    def __str__(self):
         return self.user.username

views.py

    class UserUpdateView(UpdateView):
        fields = ('first_name','last_name','email','photo')
        model = UserProfile
        success_url = reverse_lazy("NewApp:logindex")
Srvastav4
  • 177
  • 2
  • 12
  • Please, share the errors you're facing with the traceback if possible. Also, please be more explicit on what you need/want to do – Higor Rossato Jul 23 '19 at 10:18

2 Answers2

0

Use form_valid method to do so -

class UserUpdateView(UpdateView):
        form_class = UserProfileForm
        model = UserProfile
        success_url = reverse_lazy("NewApp:logindex")
        def form_valid(self, form):
             user_pro = form.instance
             user_pro.user.field_name = form.field_name
             ...
             return super(UserUpdateView, self).form_valid(form)

Note: If you want to use additional fields in forms you have to create a form say UserProfileForm and add their additional fields in forms.py, see here - dynamically add field to a form

Pankaj Sharma
  • 2,185
  • 2
  • 24
  • 50
0

There's no inheritance, User and UserProfile are different models related by a OneToOneField. So your view is actually updating two models.

Don't use the generic UpdateView which is for updating one model. It's giving you errors because the fields last_name, first_name and email don't exist for UserProfile.

Use the plain View, create the two model forms (one for User and one for UserProfile), render them both in your get() and post() methods and validate them both in your post() method.

dirkgroten
  • 20,112
  • 2
  • 29
  • 42