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

标签 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)

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

最佳答案

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

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

关于python - 使用自定义字段扩展用户模型表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10242424/

相关文章:

python - Django formtools 向导生成空白页(未返回错误)

django - ValueError - 无法创建消火栓,因为数据未验证

Python __init__.py 与 sys.path.append/insert

python - 如何在多个定界符上拆分一个字符串但只捕获一些?

python - 如何截断 Mdeditor 的内容(内容为 markdownx) - Django

python - 我怎样才能加快这个 django orm 生成的查询?

python - 尝试访问 formset.cleaned_data.get ['field' 时出现类型错误]

Python 3.4,无法访问使用 exec() 创建的变量

Python 将字典值扩展到列表

django - 带嵌套过滤器的Django注释