在同一表格上更新用户和用户个人资料 [英] update user and user profile on same form

查看:101
本文介绍了在同一表格上更新用户和用户个人资料的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为一些其他用户信息创建了userProfile。这是我的模型:

i created userProfile for some additional user information. here my model:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    picture = models.ImageField(upload_to=get_upload_path, blank=True)

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

def create_user_profile(sender, **kwargs):
    u = kwargs["instance"]
    if not UserProfile.objects.filter(user=u):
        UserProfile(user=u).save()

post_save.connect(create_user_profile, sender=User)

我需要设置页面,在此页面中,我将同时更新用户和用户配置文件字段的某些字段。这是我的表单:

I need settings page and in this page i will update some fields of user and user profile fields at the same time. Here my forms:

class UpdateUserForm(ModelForm):
    class Meta:
        model = User
        fields = ['first_name', 'last_name']

class UpdateUserProfileForm(ModelForm):
    class Meta:
        model = UserProfile
        exclude = ['user']

我的模板中有一个表单,相关功能为:

i have one form in my template and related function is:

def post(self, request, *args, **kwargs):
    update_user_form = UpdateUserForm(data=request.POST, instance=request.user)
    update_user_profile_form = UpdateUserProfileForm(data=request.POST)
    if update_user_form.is_valid() and update_user_profile_form.is_valid():
        user = update_user_form.save()
        userProfile = update_user_profile_form.save(commit=False)
        userProfile.user = user
        userProfile.save()

在这种情况下,我收到列user_id不是唯一的错误。为什么要尝试为此用户添加新的用户个人资料?

in this case i am getting "column user_id is not unique" error. why this is trying to add new user profile with this user?

这种情况下的最佳做法是什么?

what is best practice for this case?

谢谢

推荐答案

我前一段时间也遇到了同样的问题。最后,我选择更改自定义用户模型以使其继承自AbstractUser(有关更多信息,请参见: https://docs.djangoproject.com/en/dev/topics/auth/customizing/ ),而不是将其链接到具有onetoonefield的用户:

I had the same problem a while ago. In the end I opted to change my custom user model to make it inherit from AbstractUser (more info on this here: https://docs.djangoproject.com/en/dev/topics/auth/customizing/) instead of linking it to User with a onetoonefield:

models.py:

models.py:

class CustomUser(AbstractUser):
    picture = models.ImageField(upload_to=get_upload_path, blank=True)

views.py:

class UpdateUser(LoginRequiredMixin, UpdateView):
    model = CustomUser
    fields = ('first_name', 'last_name', 'picture')
    template_name = 'user/edit.html'
    success_url = reverse_lazy('forum:top')

这篇关于在同一表格上更新用户和用户个人资料的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆