如何使用更新视图更新包含用户模型的模型?

时间:2019-08-01 08:22:27

标签: django django-models django-forms django-views

我需要更新UserProfile表单,但是由于它包含用户模型,因此我不知道该怎么做。我尝试了一个代码,但是在那种情况下,只有用户配置文件表单包含实例,而没有用户表单。请帮助。

模型

class UserProfile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    mobile = models.CharField(validators=[phone_regex], max_length=17, null=True,blank=True)
    address = models.CharField(max_length=255,null=True,blank=True)
    city = models.CharField(max_length=100)
    is_active = models.BooleanField(default=True)
    role = models.ForeignKey(Role, on_delete=models.CASCADE)
    slug = models.SlugField(unique=False, blank=True)

观看次数

class AddUserProfile(FormView):
@method_decorator(user_passes_test(lambda u: u.is_superuser, login_url=LOGIN_URL))
def dispatch(self, *args, **kwargs):
    return super(AddUserProfile, self).dispatch(*args, **kwargs)
login_required = True
form_class =  UserForm
template_name = 'user_form.html'

def form_valid(self, form):
    if form.is_valid :
        user = User()
        user.username = self.request.POST.get('username')
        user.set_password(self.request.POST['password1'])
        user.email = self.request.POST['email']
        user.first_name = self.request.POST['firstname']
        user.last_name = self.request.POST['lastname']
        user.is_superuser=False
        user.save()
        userprofile = form.save(commit=False)
        userprofile.user = user
        if str(userprofile.role).lower() != 'client':
            print(userprofile.role)
            user.is_staff = True
            user.save()
        else:
            userprofile.user.is_staff = False
            user.save()
        userprofile.save()
        messages.success(self.request,'Successfully Added')
    return HttpResponseRedirect('/qworky/UserList/')

0 个答案:

没有答案