我准备了一个有关系的模特。 我想获得一个表单,可以为该表单创建用户。
有人可以解释一下如何解决它吗?
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True, primary_key=True)
website = models.URLField(null=True, blank=True)
accepted_rules = models.BooleanField(default=False)
accepted_rules_date = models.DateTimeField(auto_now_add=True)
class UserProfile(ModelForm):
class Meta:
model = UserProfile
@csrf_protect
def register(request):
if request.method == "POST":
form = UserProfile(request.POST or None)
if form.is_valid():
website = form.cleaned_data['website']
accepted_rules = form.cleaned_data['accepted_rules']
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
form.save()
print "All Correct"
return TemplateResponse(request, 'base.html', {
'form':form,
}
)
答案 0 :(得分:1)
这是我要考虑的一种方式。首先,我将其命名为UserProfileForm形式,以便它的名称不与模型冲突。在UserProfile表单中添加额外字段,以获取创建新用户所需的字段。创建新的用户实例。使用form.save(commit = False),以便您可以将新创建的User实例添加到UserProfile实例并保存。可能会有更优雅的方式。
from django import forms
class UserProfileForm(forms.ModelForm):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput())
email = forms.EmailField()
class Meta:
model = UserProfile
from django.contrib.auth.models import User
@csrf_protect
def register(request):
if request.method == "POST":
form = UserProfileForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = User(username=username, email=email)
user.set_password(password)
user.save()
user_profile = form.save(commit=False)
user_profile.user = user
user_profile.save()
print "All Correct"
return TemplateResponse(request, 'base.html', {'form':form})