2012-04-20 62 views
1

在註冊時,我想要求用戶爲:擴展與自定義字段用戶模型形式

  • 全名(我想將其保存爲雖然姓和名)
  • 公司名稱
  • 電子郵件
  • 密碼

我已經通過幾十個在計算器上類似的情況讀取。在models.py,我擴展了用戶模型像這樣:

# models.py 
class UserProfile(models.Model): 
    company = models.CharField(max_length = 50) 
    user = models.OneToOneField(User) 

def create_user_profile(sender, instance, created, **kwargs): 
    if created: 
    profile, created = UserProfile.objects.get_or_create(user=instance) 

post_save.connect(create_user_profile, sender=User) 

來源:Extending the User model with custom fields in Django

我還補充說:

# models.py 

class SignupForm(UserCreationForm): 
    fullname = forms.CharField(label = "Full name") 
    company = forms.CharField(max_length = 50) 
    email = forms.EmailField(label = "Email") 
    password = forms.CharField(widget = forms.PasswordInput) 

class Meta: 
    model = User 
    fields = ("fullname", "company", "email", "password") 

def save(self, commit=True): 
    user = super(SignupForm, self).save(commit=False) 
    first_name, last_name = self.cleaned_data["fullname"].split() 
    user.first_name = first_name 
    user.last_name = last_name 
    user.email = self.cleaned_data["email"] 
    if commit: 
    user.save() 
    return user 

而且在views.py:

# views.py 

@csrf_exempt 
def signup(request): 
    if request.method == 'POST': 
    form = SignupForm(request.POST) 
    if form.is_valid(): 
     new_user = form.save() 
     first_name, last_name = request.POST['fullname'].split() 
     email = request.POST['email'] 
     company = request.POST['company'], 
     new_user = authenticate(
     username = email, 
     password = request.POST['password'] 
    ) 
     # Log the user in automatically. 
     login(request, new_user) 

現在,它不存儲公司名稱。我怎麼做?

回答

2
user_profile = new_user.get_profile() 
user_profile.company = company 
user_profile.save() 

不要忘了配置設置您的用戶配置類,以便Django知道什麼對user.get_profile返回()

+0

完美,謝謝! – Konrad 2012-04-21 04:23:19

相關問題