[英]Django OneToOne Profile/User relationship not saving
I'm trying to set up a Django blogging app to use a one to one relation from User's to a Profile model in order to capture mode information than the default Django User model. 我试图设置一个Django博客应用程序,以使用从User到Profile模型的一对一关系,以捕获模式信息,而不是默认的Django User模型。 The problem Im having is that my Profile model isn't saving, and my profile table remains unchanged despite successfully signing up a User.
我遇到的问题是我的个人资料模型没有保存,即使成功注册了用户,我的个人资料表仍保持不变。 Here's my view where this happens:
这是我的看法:
@transaction.atomic
def profile_new(request):
if request.method == "POST":
user_form = UserForm(request.POST)
profile_form = ProfileForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save(commit=False)
profile = profile_form.save(commit=False)
user.username = user.email
user.set_password(user.password)
user.save()
profile.user = user
profile.save()
return redirect('profile_detail', pk=user.pk)
else:
messages.error(request, ('Please correct the error below.'))
else:
user_form = UserForm()
profile_form = ProfileForm()
return render(request, 'accounts/update.html', {
'user_form': user_form,
'profile_form': profile_form
})
Pretty straightforward, runs with no errors at all, it just never actually saves the Profile object. 非常简单,运行完全没有错误,它实际上从未保存过Profile对象。 heres the forms:
继承人的形式:
from django import forms
from .models import User, Profile
class UserForm(forms.ModelForm):
"""confirm_password = forms.CharField()"""
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'password')
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('bio', 'birth_date', 'avatar', 'location')
And the model for Profile: 以及Profile的模型:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
bio = models.TextField(max_length=500, blank=True)
avatar = models.ImageField(upload_to = 'avatars/', default = 'avatars/default.jpg')
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
Does anyone see any reason why Profile wouldn't save? 有谁看到个人资料无法保存的任何原因? My second question is: whats the right way to save and hash that password?
我的第二个问题是:保存和哈希该密码的正确方法是什么? I've figured out I can add a temporary 'confirm password' field to the form, but I'm not how to hash and save the password I get.
我已经知道我可以在表单中添加一个临时的“确认密码”字段,但是我不是如何散列和保存我获得的密码。
Try code below: 请尝试以下代码:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True,null=True)
I think your profile table can not save the new record if user
field is empty! 我认为如果
user
字段为空,您的个人资料表将无法保存新记录!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.