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

2024-04-25 16:37:06 发布

您现在位置:Python中文网/ 问答频道 /正文

注册后,我想请求用户:

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

我在StackOverflow上读过很多类似的情况。在模型.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

我还补充道:

^{pr2}$

在视图.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)

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


Tags: pyform名称newifmodelsrequestcreate
1条回答
网友
1楼 · 发布于 2024-04-25 16:37:06
user_profile = new_user.get_profile()
user_profile.company = company
user_profile.save()

别忘了在设置中配置UserProfile类,这样Django就知道返回什么了user.get_配置文件()

相关问题 更多 >