有人可以告诉我,为什么这段代码不起作用? 我正在尝试为用户创建注册表单。
我收到错误
" / signup / client / 2 / User上的RelatedObjectDoesNotExist没有配置文件。"
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>
models.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)
答案 0 :(得分:2)
您需要创建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
})
# ^^^^^^
答案 1 :(得分:1)
您应该在脚本中添加以下行:
profile = Profile.objects.create(user=request.user)
答案 2 :(得分:0)
我认为这段代码是从“ Django by Examples”引用的。如果是这样,请转到您的应用程序管理站点,并在配置文件帐户下手动添加一个配置文件,然后再次运行服务器。这样可以解决问题。
答案 3 :(得分:0)
在开发过程中最好和最简单的方法是: