使用自定义字段扩展用户模型表单

时间:2012-04-20 08:02:29

标签: python django django-forms

注册后,我想请求用户:

  • 全名(我想将其保存为名字和姓氏)
  • 公司名称
  • 电子邮件
  • 密码

我已经阅读了StackOverflow上的几十个类似情况。在models.py中,我像这样扩展User模型:

# 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)

现在,它不存储公司名称。我该怎么做?

1 个答案:

答案 0 :(得分:2)

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

不要忘记在设置中配置UserProfile类,以便Django知道在user.get_profile()上返回什么内容