【问题标题】:django edit user and userprofile objectdjango编辑用户和userprofile对象
【发布时间】:2012-06-24 15:05:21
【问题描述】:

所以我在 django 中创建了一个通用的“帐户”页面。我使用了 django-registration 插件,目前有一个(djang-standard)用户对象,以及一个 UserProfile 和 UserProfileForm 对象。

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

我打算做的是从 request.user 创建 UserProfile 即:

form = UserProfileForm(instance=User)

(并将该表单发送到视图),并在 UserProfileForm 中:

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']

我的 UserProfile 很像这样:

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。但是忽略这一点 - 因为我确定我应该使用 mixins - 上面的“对吗?”或者有什么建议吗?

干杯!

【问题讨论】:

    标签: django


    【解决方案1】:

    看看user profiles on the django docs,那里列出了基础知识。你也应该看看using a form in a view

    一些具体的反馈:

    • 您的 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 的实例来初始化ModelForm,而不是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)
          # ...
      
    • 您的 ModelForm 中不需要 init 覆盖。无论如何,您将使用 UserProfile 实例调用它。如果要创建新用户,只需调用 User 构造函数即可:

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

    【讨论】:

    • 仅供参考,截至今天,AUTH_PROFILE_MODULE 和 get_profile 已被弃用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 2016-07-14
    • 1970-01-01
    • 2017-11-14
    • 2011-08-31
    • 1970-01-01
    • 2019-04-02
    相关资源
    最近更新 更多