2012-01-29 161 views
1

我無法在用戶提交表單時獲取first_name和last_name變量進行保存。這是我的代碼,我需要幫助。姓氏和姓氏未保存在自定義Django_Registration表單中

Models.py

from django.db import models 
from django.contrib.auth.models import User 

class MyRegistration(models.Model): 
    first_name = models.CharField(max_length = 100, null = True, unique = True) 
    last_name = models.CharField(max_length = 100, null = True, unique = True) 

def __unicode__(self): 
    return self.name 

Forms.py

from registration.forms import RegistrationForm 
from django.forms import ModelForm 
from models import MyRegistration 
from django import forms 

class MyRegistrationForm(forms.ModelForm): 
    class Meta: 
    model = MyRegistration 


RegistrationForm.base_fields.update(MyRegistrationForm.base_fields) 

class CustomRegistrationForm(RegistrationForm): 
    def save(self, profile_callback = None): 
    user = super(CustomRegistrationForm, self).save(profile_callback = None) 
    org, c = MyRegistration.objects.get_or_create(user=user, first_name = 
    self.cleaned_data['first_name'], last_name = self.cleaned_data['last_name']) 

在根urls.py

url(r'^accounts/register/$', 'registration.views.register', {'form_class':   
    CustomRegistrationForm, 'backend':'registration.backends.default.DefaultBackend'}), 

回答

1

這是一個非常奇怪的方式去做這件事,似乎有一些交叉的電線。首先,如果您希望保存一些關於用戶的額外數據,則不應該通過註冊模型完成 - 您應該創建一個處理額外數據的應用程序profile。 Django文檔have some good suggestions on how to go about this

更重要的是,默認User對象,你更有可能再創造您的用戶已經有字段first_namelast_name,所以你可以使用它們,而不是創建一個新的配置模式