2012-04-21 89 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