我想创建一个扩展的用户模型。我已经创建了一个与默认django用户模型具有一对一关系的配置文件模型。问题是,当我创建一个Profile实例并包含User字段时,它引起我(NOT NULL约束失败:portal_profile.user_id)例外。为什么?
view.py
def register(request):
if request.method == 'POST':
user_form= UserCreationForm(request.POST)
profile_form = ProfileForm(request.POST, request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save(commit=False)
profile_form.user=user_form
profile_form.save()
model.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True)
img = models.ImageField(null=True, upload_to='userImg')
country = models.CharField(null=True, max_length=50)
city = models.CharField(null=True, max_length=50)
email=models.EmailField(unique=True)
forms.py
class ProfileForm(ModelForm):
img=forms.ImageField(required=False)
class Meta:
model = Profile
fields=['img', 'country', 'city', 'email']
register.html
{% if UserForm.errors or ProfileFrom.errros %}
<p> Error </p>
{% endif %}
{{ UserForm }}
{{ ProfileForm }}
答案 0 :(得分:0)
对于用户和个人资料,您都将模型实例与表单相混淆。应该是:
user = user_form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()