/ accounts / regist /的KeyError /

时间:2017-02-16 13:58:02

标签: python django django-forms

我收到了一个错误:

  

/ accounts / regist /'电子邮件'。

中的KeyError

之前,我的用户注册表单只有用户名和密码列。我想在其中添加电子邮件表单,所以我写了它。但我得到了错误。我导入了:

django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm.

我的auth_user表有电子邮件列,所以我不知道如何修复它。 我在test.py中写道

from django.test import TestCase

# Create your tests here.
class UserTests(APITestCase):
    def setUp(self):
        """
        setUp for testing
        """
        User.objects.create(username='user1', email='email1', password='user1')
        User.objects.create(username='user2', email='email2',password='user2')
        self.user1 = User.objects.get(username='user1')
        self.user2 = User.objects.get(username='user2')
在serializers.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username','email', 'password')
        write_only_fields = ('password')
        read_only_fields = ('id')

        def create(self, validated_data):
          password = validated_data.get('password')
          validated_data['password'] = make_password(password)
          return User.objects.create(**validated_data)

在forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm

class RegisterForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['class'] = 'form-control'
        self.fields['email'].widget.attrs['class'] = 'form-control'
        self.fields['password1'].widget.attrs['class'] = 'form-control'
        self.fields['password2'].widget.attrs['class'] = 'form-control'

在这些代码中,我指定了电子邮件列。那么,我该怎么做才能解决它?

回溯显示

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/exception.py in inner
  39          response = get_response(request) 
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py in _get_response
187         response = self.process_exception_by_middleware(e, request) 
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py in _get_response
185        response = wrapped_callback(request, *callback_args, **callback_kwargs) 
accounts/views.py in regist
65         form = RegisterForm(request.POST or None) 
▶ Local vars
accounts/forms.py in __init__
11      self.fields['email'].widget.attrs['class'] = 'form-control' 
▶ Local vars

1 个答案:

答案 0 :(得分:0)

根据您的部分堆栈跟踪,在尝试为电子邮件字段定义窗口小部件时,您的代码会出现窒息。但那个领域定义在哪里?它没有在任何地方定义。您的代码应更改为:

class RegisterForm(UserCreationForm):
    email = forms.EmailField(required = True)
    def __init__(self, *args, **kwargs):
        ....