2

我准备了一个有关系的模型。我想要一个可以为该表单创建用户的表单。

有人可以解释一下如何解决吗?

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,
                             }
                            )
4

1 回答 1

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})
于 2012-04-21T04:43:30.073 回答