2012-04-21 84 views
2

我准备了一个关系模型。 我想获得一个可以为该表单创建用户的表单。Django:创建有关系的表格

有人可以解释我如何解决?

class UserProfile(models.Model): 
    user = models.OneToOneField(User, unique=True, primary_key=True) 
    website = models.URLField(null=True, blank=True) 
    accepted_rules = models.BooleanField(default=False) 
    accepted_rules_date = models.DateTimeField(auto_now_add=True) 


class UserProfile(ModelForm): 
    class Meta: 
     model = UserProfile 

@csrf_protect 
def register(request): 
    if request.method == "POST": 

     form = UserProfile(request.POST or None) 
     if form.is_valid(): 
      website = form.cleaned_data['website'] 
      accepted_rules = form.cleaned_data['accepted_rules'] 

      username = form.cleaned_data['username'] 
      email = form.cleaned_data['email'] 
      password = form.cleaned_data['password'] 



      form.save() 


      print "All Correct"    


    return TemplateResponse(request, 'base.html', { 
          'form':form, 
          } 
          ) 

回答

1

这是我会考虑的一种方法。首先,我将命名为UserProfileForm,以便它的名称不与模型冲突。将额外字段添加到您的UserProfile表单中,以获取创建新用户所需的字段。创建新的用户实例。使用form.save(commit = False),以便您可以将新创建​​的User实例添加到UserProfile实例并保存。可能有更优雅的方式。

from django import forms 

class UserProfileForm(forms.ModelForm): 

    username = forms.CharField() 
    password = forms.CharField(widget=forms.PasswordInput()) 
    email = forms.EmailField() 

    class Meta: 
     model = UserProfile 

from django.contrib.auth.models import User 

@csrf_protect 
def register(request): 
    if request.method == "POST": 
     form = UserProfileForm(request.POST) 
     if form.is_valid(): 
      username = form.cleaned_data['username'] 
      email = form.cleaned_data['email'] 
      password = form.cleaned_data['password'] 
      user = User(username=username, email=email) 
      user.set_password(password) 
      user.save() 
      user_profile = form.save(commit=False) 
      user_profile.user = user 
      user_profile.save() 
      print "All Correct"    
return TemplateResponse(request, 'base.html', {'form':form}) 
+1

请注意'用户名(用户名,密码,电子邮件)'用法不正确。你需要传递名为参数的模型类,例如'username = username'来工作:通常'pk'是构造函数的第一个参数,因此实际上你得到一个User()w /'pk'设置为username。此外,refs [post](http://stackoverflow.com/questions/10246463/password-hashers-setting-in-django/10246947#10246947),不要使用'password = ...',这已经隐式地在你的代码中完成,用于'User'构造。 – okm 2012-04-21 11:32:36

+0

@okm,绝对好,赶上。我正在混合User.objects.create_user(),仍然有错误的参数顺序,并在上面编辑以反映正确的密码设置。 – 2012-04-22 02:00:14

+0

是否应该在视图中处理关系?将所有这些封装在表单中似乎更合乎逻辑。我还没有看到有关它的许多文档...... – unflores 2015-04-08 10:14:01