ModelForm需要用户才能创建一个:is_valid()返回false

时间:2014-02-23 20:47:11

标签: python django-forms django-1.6

我正在尝试为Django应用程序创建一个自定义用户,并且遇到了一个耗费时间的小问题。我会切入追逐:

我的Django版本是1.6.2和python 2.7.4

这是模型

class Account(models.Model):
    user = models.OneToOneField(User)
    game_id = models.PositiveIntegerField(null=True, blank=True, default=None)
    avatar = models.ImageField()
    desc = models.CharField(max_length=2500, null=True, blank=True, default=None)

ModelForm:

    class RegistrationForm(ModelForm):
        game_name = forms.CharField(label=(u'In Game Name'))
        email = forms.EmailField(label=(u'Email Address'))
        password = forms.CharField(label=(u'Password'), 
            widget=forms.PasswordInput(render_value=False))
        password1 = forms.CharField(label=(u'Verify Password'), 
            widget=forms.PasswordInput(render_value=False))

        class Meta:
            model = Account
            exclude = ('user',)

        def clean_game_name(self):
            username = self.cleaned_data['game_name']
            try:
                User.objects.get(username=username)
            except User.DoesNotExist:
                return username
            raise forms.ValidationError("That username is already taken, please select another.")

        def clean(self):
            if self.cleaned_data['password'] != self.cleaned_data['password1']:
                raise forms.ValidationError("The passwords did not match.  Please try again.")
            return self.cleaned_data

观点:

def account_registration(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/account/profile/')
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid(): # returns false
            user = User.objects.create_user(
                username=form.cleaned_data['game_name'],
                email=form.cleaned_data['email'],
                password=form.cleaned_data['password'])
            user.save()
            member = Account(user=user)
            member.save()
            return HttpResponseRedirect('/account/profile/')
        else:
            print form.errors # output below
            return render_to_response('account/register.html', {'form': form}, context_instance=RequestContext(request))
    else:
        form = RegistrationForm()
        context = {'form': form}
        return render_to_response('account/register.html', context, context_instance=RequestContext(request))

打印输出:

user: This field is required. 

如何为RegistrationForm提供一个User对象,该对象在注册表单经过验证后才会存在?我对python和django都是全新的,所以我认为解决方案非常明显。

编辑:添加模板

<form action="" method="post">
{% csrf_token %}
{% if form.errors %}<p>Please correct the following fields:</p>{% endif %}
<div class="register_div">
        {% if form.game_name.errors %}<p class="error">{{ form.game_name.errors }}</p>{% endif %}
        <p><label for="game_name"{% if form.game_name.errors %} class="error"{% endif %}>In Game Name:</label></p>
        <p>{{ form.game_name }}</p>
</div>
<div class="register_div">
        {% if form.email.errors %}<p class="error">{{ form.email.errors }}</p>{% endif %}
        <p><label for="email"{% if form.email.errors %} class="error"{% endif %}>Email:</label></p>
        <p>{{ form.email }}</p>
</div>
<div class="register_div">
        {% if form.password.errors %}<p class="error">{{ form.password.errors }}</p>{% endif %}
        <p><label for="password"{% if form.password.errors %} class="error"{% endif %}>Password:</label></p>
        <p>{{ form.password }}</p>
</div>
<div class="register_div">
        {% if form.password1.errors %}<p class="error">{{ form.password1.errors }}</p>{% endif %}
        <p><label for="password1"{% if form.password1.errors %} class="error"{% endif %}>Verify Password:</label></p>
        <p>{{ form.password1 }}</p>
</div>
<p><input type="submit" alt="register" /></p>
</form>

1 个答案:

答案 0 :(得分:1)

正如我在评论中提到的那样,没有理由将其作为帐户上的ModelField。虽然您在valid子句中创建了一个Account,但实际上并不是从表单本身的任何字段中创建。您应该将其设置为普通表单(继承自forms.Form并删除Meta类):其余代码保持完全相同,并且仍将创建用户和帐户实例。

那就是说,我仍然不确定为什么代码应该给出错误。您已排除用户字段,因此不应要求表单有效。