first_name和last_name不保存在自定义Django_Registration表单中

时间:2012-01-29 23:43:33

标签: django django-admin django-forms django-registration

我无法在用户提交表单后获取要保存的first_name和last_name变量。这是我的代码。我需要帮助。

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

在root urls.py

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

1 个答案:

答案 0 :(得分:1)

这是一个非常奇怪的方法,似乎有一些交叉的电线。首先,如果您希望保存一些有关用户的额外数据,则不应通过注册模型完成 - 您应该创建一个处理额外数据的profile应用程序。 django docs have some good suggestions on how to go about this

更重要的是,您可能为用户创建的默认User对象已包含first_namelast_name字段,因此您可以使用它们而不是创建新的配置文件模型