PlayerForm.is_valid始终为false,但玩家仍在保存

时间:2019-05-09 22:54:32

标签: python html django

我设计了一个排行榜应用,其中包含玩家和游戏。

注册时,它将创建Django用户并创建与该用户关联的Player对象。当我注册时,如果PlayerForm.is_validTrue,则会在PlayerForm(UserCreationForm)的位置创建用户和播放器,并呈现elosearch.html,否则,将返回{{1} }。

我可以看到正在创建播放器和用户,但是当我提交请求时,它正在渲染register.html而不是register.html。如果elosearch.html产生了is_valid,如何渲染错误的视图?如果不生成,为什么要节省播放器和用户?我创建了自己的html表单,因此实际上不需要将表单传递给模板(不使用args)

PlayerForm

True

注册视图

class PlayerForm(UserCreationForm):
    username = forms.CharField(required=True)
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = (
            'username',
            'email',
            'password1',
            'password2',
        )

    def save(self, commit=True):
        user = super(PlayerForm, self).save(commit=False)
        user.username = self.cleaned_data['username']
        user.email = self.cleaned_data['email']
        user.password1 = self.cleaned_data['password1']
        user.password2 = self.cleaned_data['password2']
        new_player = Player(name=str(user.username), user=user)

        if commit:
            user.save()
            new_player.save()

        return user

我可以看到正在创建播放器和用户,但是当我提交请求时,它正在渲染def register(request): if request.method == 'POST': form = PlayerForm(request.POST) if form.is_valid(): form.save() return render(request, 'elousers/elosearch.html') else: return render(request, 'elousers/register.html') else: form = PlayerForm() args = {'form': form} return render(request, 'elousers/register.html', args) 而不是register.html

0 个答案:

没有答案