0

目标:我正在尝试创建一个超级简单的用户注册表单。

我收到以下错误:local variable 'NewUserRegistrationForm' referenced before assignment

我在forms.py有一个表格:

class NewUserRegistrationForm(UserCreationForm):
    username = forms.CharField(required=True,max_length=30,validators=[RegexValidator('^[A-Za-z0-9]{1,30}$','e.g. must be 30 characters or less','Invalid Entry')])
    email = forms.EmailField(required=True, max_length=75)
    password = forms.PasswordInput()
    class Meta:
        model = User
        fields = ("username", "email", "password1","password2")

def save(self, commit=True):
    user = super(NewUserRegistrationForm, self).save(commit=False)
    user.username = self.cleaned_data["username"]
    user.email = self.cleaned_data["email"]
    user.password = self.cleaned_data["password1"]
    if commit:
        user.save()
    return user

form = NewUserRegistrationForm()

视图.py

def Registration(request):
    NewUserRegistrationForm = NewUserRegistrationForm(request.POST or None)
    if request.method == 'POST':
        if NewUserRegistrationForm.is_valid():
            NewUserRegistrationForm.save()
            return HttpResponseRedirect("/Login/")

        return render(request, 'my/reuse/register.html', {
            'NewUserRegistrationForm': NewUserRegistrationForm 
        })

我在这里做错了什么?

谢谢

4

1 回答 1

0

这是我的一个超级愚蠢的错误。

我将视图定义切换为:

 def Registration(request):
    MyForm = NewUserRegistrationForm(request.POST or None)
    if request.method == 'POST':
        if MyForm.is_valid():
            MyForm.save()
            return HttpResponseRedirect("/Login/")

    return render(request, 'VA/reuse/register.html', {
        'NewUserRegistrationForm': NewUserRegistrationForm 
    })

return render()必须与我保持一致,我不得不将if request.method表单重命名为我的表单声明以外的其他名称NewUserRegistrationForm

于 2013-09-14T21:31:02.947 回答