python - Django 使用用户配置文件扩展用户(错误 : User has no profile.)

标签 python django django-forms django-registration

enter image description here有人可以告诉我,为什么这段代码不起作用? 我正在尝试为用户创建注册表单。

I'm getting an error

"RelatedObjectDoesNotExist at /signup/client/2/ User has no profile."

View .py

if request.POST:
            user_form = UserCreationForm(request.POST)
            profile_form = ProfileForm(request.POST)
            if user_form.is_valid() and profile_form.is_valid():
                user = user_form.save()
                user.profile.city="WW"
                user.profile.phone="32323"
                user.profile.save()

表单.py

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ( 'city', 'phone')

html文件

  <h2>Sign up</h2>
  <form method="post">
    {% csrf_token %}
    {{ user_form.as_p }}
    {{ profile_form.as_p }}
    <button type="submit">Sign up</button>

模型.py

from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    city = models.TextField(max_length = 50)
    phone = models.TextField(max_length = 12)

最佳答案

您需要创建一个profile,它不会在您保存user_form时创建

        user_form = UserCreationForm(request.POST)
        profile_form = ProfileForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            Profile.objects.create(**{
                 'city':"WW", 'phone': '32323', 'user': user
            })
            # ^^^^^^

关于python - Django 使用用户配置文件扩展用户(错误 : User has no profile.),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45745226/

相关文章:

python - 如何在此服务器中实现 Websocket 握手?

python - 使用 Direct Kafka API 运行 Spark 流应用程序所需的最佳资源是什么?

python - 煎饼排序中最短翻转序列的计数

python - Tensorflow - 可视化预训练网络的学习过滤器

django - 当关系包含属性时,如何在django中实现多对多关系?

python - Django | OperationalError : MySQL Connection not available, 在页面重新加载时消失,怎么了?

python - 更改 Django 外键中的 UUID 格式

python - 如何将 optgroups 添加到 django ModelMultipleChoiceField?

python - 将 2 个值传递给验证器

django - 动态填充表单集中的字段