简体   繁体   中英

KeyError: 'password1': password1 = self.cleaned_data['password1']

I am trying to implement registration in Django and faced with error:

forms.py line 17, in clean_password

KeyError: 'password1': password1 = self.cleaned_data['password1']

How can I solve the error?

Full code of the application located here (branch Login-version-2-site ): https://github.com/mascai/reg_app/tree/Login-version-2-site

models.py

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.dispatch import Signal
from .utilities import send_activation_notification


class AdvUser(AbstractUser):
    is_activated = models.BooleanField(default=True, db_index=True,
                                       verbose_name='Пpoшeл активацию?')
    send_messages = models.BooleanField(default=True, verbose_name='Слать оповещения о новых комментариях?')

class Meta(AbstractUser.Meta):
        pass


user_registrated = Signal(providing_args=['instance'])


def user_registrated_dispatcher(sender, **kwargs):
    send_activation_notification(kwargs['instance'])


user_registrated.connect(user_registrated_dispatcher)

forms.py

class RegisterUserForm(forms.ModelForm):
    email = forms.EmailField(required=True, label="Email address")
    password1 = forms.CharField(label="Password", widget=PasswordInput,
                                help_text=password_validation.password_validators_help_text_html())
    password2 = forms.CharField(label="Password", widget=PasswordInput,
                                help_text=password_validation.password_validators_help_text_html())

    def clean_password(self):
        password1 = self.cleaned_data['password1']
        if password1:
            password_validation.validate_password(password1)
        return password1

    def clean(self):
        super().clean()
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2 and password1 != password2:
            errors = {'password2': ValidationError('Введённые пароли не совпадают', code='password_mismatch')}
            raise ValidationError(errors)
        else:
            return self.cleaned_data


    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        user.is_active = False
        user.is_activated = False
        if commit:
            user.save()
        user_registrated.send(RegisterUserForm, isinstance=user)
        return user

    class Meta:
        model = AdvUser
        fields = ('username', 'email', 'password', 'password2',
                  'first_name', 'last_name', 'send_messages')

urls.py

from .views import BBLoginView, BBLogoutView, profile, RegisterUserView, RegisterDoneView, user_activate

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('accounts/login/', BBLoginView.as_view(), name='login'),
    path('accounts/profile/', profile, name='profile'),
    path('accounts/logout/', BBLogoutView.as_view(), name='logout'),

    path('accounts/register/done', RegisterDoneView.as_view(), name='register_done'),
    path('accounts/register/', RegisterUserView.as_view(), name='register'),
    path('accounts/register/activate/<str:sign>/', user_activate, name='register_activate'),
]

views.py

def post_list(request):
    return render(request, 'blog/post_list.html', {})


class BBLoginView(LoginView):
    template_name = 'blog/login.html'

class BBLogoutView(LoginRequiredMixin, LogoutView):
    template_name = 'blog/logout.html'

@login_required
def profile(request):
    return render(request, 'blog/profile.html')

class RegisterUserView(CreateView):
    model = AdvUser
    template_name = 'blog/register_user.html'
    form_class = RegisterUserForm
    success_url = '/register_done'

class RegisterDoneView(TemplateView):
    template_name = "blog/register_done.html"


def user_activate(request, sign):
    try:
        username = signer.unsign(sign)
    except:
        return render(request, 'blog/bad_signature.html')
    user = get_object_or_404(AdvUser, username=username)
    if user.is_activated:
        template = 'blog/user_is_activated.html'
    else:
        template = 'blog/activation_done.html'
        user.is_active = True
        user.is_activated = True
        user.save()
    return render(request, template)

In a Django form every clean_<field_name> can safely handle only <field_name> , there is no guarantee that another field is available in cleaned_data at that point, it's available only if it has been already cleaned.

Since what you want to do is to clean password1 , rename clean_password to clean_password1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM