Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django使用userprofile扩展用户(错误:用户没有配置文件。)_Python_Django_Django Forms_Django Registration - Fatal编程技术网

Python Django使用userprofile扩展用户(错误:用户没有配置文件。)

Python Django使用userprofile扩展用户(错误:用户没有配置文件。),python,django,django-forms,django-registration,Python,Django,Django Forms,Django Registration,有人会告诉我,为什么这个代码不起作用? 我正在尝试为用户创建一个注册表 我犯了个错误 “位于/signup/client/2/User的RelatedObjectsDoesNotExister没有配置文件。” views.py if request.POST: user_form = UserCreationForm(request.POST) profile_form = ProfileForm(request.POST)

有人会告诉我,为什么这个代码不起作用? 我正在尝试为用户创建一个注册表

我犯了个错误

“位于/signup/client/2/User的RelatedObjectsDoesNotExister没有配置文件。”

views.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()
forms.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>

您需要创建一个
配置文件
,当您保存
用户表单

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

应在脚本中添加以下行:

profile = Profile.objects.create(user=request.user)

我相信这段代码是从“Django by Examples”中引用的。如果是这样,请转到您的应用程序管理站点,在配置文件帐户下手动添加配置文件,然后再次运行服务器。这将解决这个问题。

在开发过程中,最好也是最简单的方法是:

  • 在终端中,创建另一个超级用户-$python manage.py createsuperuser
  • 使用新凭据登录管理页面
  • 删除旧管理员或在userprofile之前创建的任何用户 创建了模型

  • 欢迎这是对贝尔布朗的回答还是评论?请澄清。这个由Yoshita Arora提供的答案为我解决了这个问题。给你!不,这是我自己的代码。手动添加配置文件?相反,它应该自动创建。在model.py中,您正在基于用户模型和OnetoOneField创建配置文件。因此,你必须从你的管理站点创建配置文件。这是一个关于如何处理数据库不一致性的建议,而不是问题的答案。请将此类建议添加为评论而不是答案。
    profile = Profile.objects.create(user=request.user)