0

我有一个允许用户注册的注册,但我很难修复它。

问题是当用户提交单个字段而不是整个表单时,例如电子邮件。我收到这个错误

KeyError at /register/

password
Request Method:     POST
Request URL:    http://127.0.0.1:8000/register/
File "C:\Python26\Lib\site-packages\django\forms\forms.py" in _get_errors
  115.             self.full_clean()
File "C:\Python26\Lib\site-packages\django\forms\forms.py" in full_clean
  271.         self._clean_form()
File "C:\Python26\Lib\site-packages\django\forms\forms.py" in _clean_form
  299.             self.cleaned_data = self.clean()
File "C:\o\17\mysite\pet\forms.py" in clean
  31.       if self.cleaned_data['password'] != self.cleaned_data['password1']:

Exception Type: KeyError at /register/
Exception Value: password

我尝试使用 if 修复此解决方案。如果用户提交了用户名或任何其他必填字段,则处理表单,否则重新显示原始表单。

但我仍然得到同样的错误。

这是我编辑的views.py (页面底部是我原来的RegistrationForm)

def PetRegistration(request):   
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('world:HappyLand'))

    if request.method =='POST':
        form = UserRegistration(request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        if username:
            email=form.cleaned_data['email']
            if email:
                password=form.cleaned_data['password']
                if password:
                    user = User.objects.create_user(
            username=form.cleaned_data['username'], 
            email=form.cleaned_data['email'], 
            password=form.cleaned_data['password']
            )
                    user.is_active = True
                    user.first_name = form.cleaned_data['name']
                    user.save()

                    person = authenticate(
            username=form.cleaned_data['username'], 
            password=form.cleaned_data['password']
            )

                    Person.objects.create(user_id=user.id, 
                    name=form.cleaned_data['name'],birthday=form.cleaned_data['birthday'])

                    login(request, person)
                    return HttpResponseRedirect(reverse('world:HappyLand'))

return render(request, 'register.html', {'form': UserRegistration()})

如何修复此错误以及如何在用户未填写的其他字段上显示错误消息,例如“错误缺少字段,请填写此字段”。

def PetRegistration(request):   
if request.user.is_authenticated():
    return HttpResponseRedirect(reverse('world:HappyLand'))

if request.method =='POST':
    form = UserRegistration(request.POST)
    if form.is_valid():
        user = User.objects.create_user(
            username=form.cleaned_data['username'], 
            email=form.cleaned_data['email'], 
            password=form.cleaned_data['password']
            )
        user.is_active = True
        user.first_name = form.cleaned_data['name']
        user.save()

        person = authenticate(
            username=form.cleaned_data['username'], 
            password=form.cleaned_data['password']
            )

        Person.objects.create(user_id=user.id, 
            name=form.cleaned_data['name'],birthday=form.cleaned_data['birthday'])

        login(request, person)
        return HttpResponseRedirect(reverse('world:HappyLand'))

return render(request, 'register.html', {'form': UserRegistration()})

我的表格.py

class UserRegistration(forms.Form):
    username = forms.CharField()
    name = forms.CharField()
    email = forms.EmailField()
    birthday = forms.DateField(widget=extras.SelectDateWidget(years=range(1950, 2012)))

    password = forms.CharField(
        widget=forms.PasswordInput(render_value=False)
        )
    password1 = forms.CharField(
        label=(u'Verify Password'), 
        widget = forms.PasswordInput(render_value=False)
        )

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

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

我的模型.py

class Person(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=100, blank=True)
    birthday = models.DateField(blank=True,null=True)
    def __unicode__(self):
        return self.name
4

2 回答 2

6

问题出在你的clean(). 在clean()中,您正在尝试访问password表单上的字段cleaned_datapasswordcleaned_data当用户填写此字段时才可用。因此,您必须在尝试访问它之前检查它password是否存在。cleaned_data

改变你的clean()

def clean(self):
    if 'password' in self.cleaned_data and 'password1' in self.cleaned_data and self.cleaned_data['password'] != self.cleaned_data['password1']:
        raise forms.ValidationError("The password does not match ")
    return self.cleaned_data

您可以在表单字段上提供关键字参数error_messages以显示错误消息,例如“错误缺少字段,请填写此字段”。

class SomeForm(forms.Form):
    name = forms.CharField(error_messages={'required':'Error Missing Field , Please Fill this Field'})

您的视图中有一个错误。

is_valid() 填充表单上的错误,但必须将同一个表单实例发送到模板,以便您可以访问表单字段上的错误。

render()但在您看来,即使发布请求中的表单无效,您也只有一个调用被调用。在此render(),您正在创建一个新的表单实例。因此,您发送到模板的这个新表单不会有任何错误。

因此,对您的视图稍作修改:

def PetRegistration(request):   
    if request.user.is_authenticated():
    return HttpResponseRedirect(reverse('world:HappyLand'))

    form = UserRegistration() #This will be used in GET request
    if request.method =='POST':
        form = UserRegistration(request.POST) #This will be used in POST request
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'], 
                email=form.cleaned_data['email'], 
                password=form.cleaned_data['password']
            )
            user.is_active = True
            user.first_name = form.cleaned_data['name']
            user.save()

            person = authenticate(
                username=form.cleaned_data['username'], 
                password=form.cleaned_data['password']
            )

            Person.objects.create(user_id=user.id, 
                name=form.cleaned_data['name'],birthday=form.cleaned_data['birthday'])

            login(request, person)
            return HttpResponseRedirect(reverse('world:HappyLand'))

    return render(request, 'register.html', {'form': form})

请注意,在您看来,我form=UserRegistration()在检查其是否为 POST 请求之前添加了注释,并在我们正在实例化的两个地方添加了注释UserRegistration。然后在render(),你应该发送这个form

然后你{{form.username.errors}}会工作。

于 2013-04-14T20:15:01.930 回答
1

我刚刚修改了你的 forms.py

class UserRegistration(forms.Form):
    username = forms.CharField()
    name = forms.CharField()
    email = forms.EmailField()
    birthday = forms.DateField(widget=extras.SelectDateWidget(years=range(1950, 2012)))
    password = forms.CharField(
        widget=forms.PasswordInput(render_value=False)
        )
    password1 = forms.CharField(
        label=(u'Verify Password'), 
        widget = forms.PasswordInput(render_value=False)
        )

    def clean(self):
        cleaned_data = super(UserRegistration, self).clean()
        username = cleaned_data.get("username")
        password = cleaned_data.get("password")
        password1 = cleaned_data.get("password1")

        #check if username exist  
        user = User.objects.filter(username=username)
        if user:
            raise forms.ValidationError(
                "That user is already taken , please select another ")

        #check password
        if password != password1:
            raise forms.ValidationError(
                "Your current and confirm password do not match.")

        return cleaned_data
于 2013-04-06T03:51:00.703 回答