Django 编辑用户和用户配置文件对象



所以我正在Django中制作一个通用的"帐户"页面。我使用了django注册插件,目前有一个(djang-standard)User对象,以及UserProfile和UserProfileForm对象。

我想这是一个风格问题,或者说是最佳实践的问题。我的计划是"正确"的还是有"更好/推荐/标准的方法"来做到这一点?

我计划做的是从request.user创建用户配置文件,即:

form = UserProfileForm(instance=User)

(并将该表单发送到视图),并在用户配置文件表单中:

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
    def __init__(self,*args,**kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        if kwargs.has_key('instance'):
            self.user = kwargs['instance']

我的用户配置文件非常像这样:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    points = models.IntegerField(default=0) #how is the user going with scores?

以及用户属于django.contrib.auth.models种类。

还行!编辑和保存的处理要么通过 mixin django 的东西来完成,要么更有可能是因为我还没有阅读我自己的用户定义视图来处理帖子和获取。但是忽略这一点 - 因为我确定我应该使用mixins - 上面的"对吗?"还是有建议?

干杯!

看看 django 文档中的用户配置文件,那里列出了基础知识。您还应该看一下如何在视图中使用窗体。

一些具体的反馈:

  • 您正确使用了 UserProfile 模型,但每次添加新用户时(通过管理界面或在一个视图中以编程方式)都必须创建一个实例。您可以通过注册用户post_save信号来执行此操作:

    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            UserProfile.objects.create(user=instance)
    post_save.connect(create_user_profile, sender=User)
    
  • 您应该使用UserProfile的实例来初始化模型窗体,而不是User。您始终可以使用request.user.get_profile()获取当前用户配置文件(如果您在 settings.py 中定义了AUTH_PROFILE_MODULE)。您的视图可能如下所示:

    def editprofile(request):
        user_profile = request.user.get_profile()
        if request.method == 'POST':
            form = UserProfileForm(request.POST, instance=user_profile)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/accounts/profile')
        else:
            form = UserProfileForm(instance=user_profile)
        # ...
    
  • 无需在模型窗体中进行初始化覆盖。无论如何,您将使用用户配置文件实例调用它。如果要创建新用户,只需调用 User 构造函数:

    user = User()
    user.save()
    form = UserProfileForm(instance = user.get_profile())
    # ...
    

最新更新