2012-06-24 90 views
1

所以我在django中制作了一个通用的“帐户”页面。我使用了django-registration插件,目前有一个(djang标准)User对象,以及一个UserProfile和UserProfileForm对象。django编辑用户和用户配置文件对象

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

什么我打算做的是创建一个从request.user即用户配置:

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

在我的用户配置是相当多的,像这样:

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

并在用户是的品种。

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

干杯!

回答

1

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

一些具体的反馈:

  • 你得到了用户配置模型正确的,但你必须创建一个实例每次添加新用户时(无论是通过管理界面或以编程方式在一个你视图)。您可以通过登录到用户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) 
    
  • 你应该初始化的的ModelForm与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) 
        # ... 
    
  • 无需在您的ModelForm的初始化覆盖。无论如何,您将用UserProfile实例调用它。如果你想创建一个新用户,只需调用用户构造:

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

FYI今天,AUTH_PROFILE_MODULE和get_profile已被弃用 – Jay

相关问题