簡體   English   中英

Key_error 在 Django 表單中使用 self.cleaned_data[]

[英]Key_error using self.cleaned_data[] in Django forms

在我的 forms.py 中,我不斷收到下面的email = self.cleaned_data["email"]的 key_error。 我還嘗試添加電子郵件驗證或 clean_email 方法,因為不知何故,key_error 似乎僅在我嘗試使用無效電子郵件地址注冊時發生 添加def clean_email()是正確的方法嗎? 如果是這樣,我班級中的 forms.py 是否適合這樣做?

表格.py:

from django import forms
from django.contrib.auth.models import User


class RegisterForm(forms.Form):
    first_name = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': "First Name", 'autocomplete': "nope"}), label="First name", max_length=64, required=True)
    last_name = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': "Last Name", 'autocomplete': "new-password"}), label="Last name", max_length=64, required=True)
    email = forms.EmailField(widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': "Email", 'autocomplete': "new-password"}), label="Email", max_length=132, required=True)
    password = forms.CharField(label="Password", max_length=32, widget=forms.PasswordInput(attrs={'class': "form-control", 'placeholder': "Password"}))
    confirmation = forms.CharField(label="Confirmation", max_length=32, widget=forms.PasswordInput(attrs={'class': "form-control", 'placeholder': "Confirm"}))

    def clean(self):
        email = self.cleaned_data["email"]
        if User.objects.filter(username=email).exists():
          raise forms.ValidationError(u'Email "%s" is already in use.' % email)

        password = self.cleaned_data["password"]
        confirmation = self.cleaned_data["confirmation"]
        if password != confirmation:
            raise forms.ValidationError("Password and confirmation do not match!")

views.py 中對應的方法是:

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.contrib import messages

def register_client(request):
  if request.method == "POST":
    form = RegisterForm(request.POST)

    if form.is_valid():
      email = form.cleaned_data['email']
      password = form.cleaned_data['password']
      user = User.objects.create_user(email, email, password)
      user.first_name = form.cleaned_data['first_name']
      user.last_name = form.cleaned_data['last_name']
      user.save()

  else:
    form = RegisterForm()

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

注冊.html:

{% extends "pizza/outerlayout.html" %}

{% block title %}
Register for Pizza
{% endblock %}

{% block body %}

<form action="{% url 'register_client' %}" class="form-signin" method="post" autocomplete="false">
  {% csrf_token %}
  {% load static %}
  <img class="mb-4" src="{% static 'pizza/pizza.jpg' %}" alt="" width="72" height="72">
  <h1 class="h3 mb-3 font-weight-normal">Register as Pizza Client</h1>
  {{ form }}

  <button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>

</form>

{% endblock %}

追溯:

Internal Server Error: /register_client
Traceback (most recent call last):
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/mnt/c/git/project3/orders/views.py", line 43, in register_client
    if form.is_valid():
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/forms/forms.py", line 179, in is_valid
    return self.is_bound and not self.errors
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/forms/forms.py", line 174, in errors
    self.full_clean()
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/forms/forms.py", line 377, in full_clean
    self._clean_form()
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/forms/forms.py", line 404, in _clean_form
    cleaned_data = self.clean()
  File "/mnt/c/git/project3/orders/forms.py", line 14, in clean
    email = self.cleaned_data["email"]
KeyError: 'email'

感謝 vm 並為基本問題道歉 - 我是新手。

嘗試這個:

def clean_email(self):   #add clean_email
    email = self.cleaned_data["email"]
    if User.objects.filter(username=email).exists():
      raise forms.ValidationError(u'Email "%s" is already in use.' % email)

密碼驗證制作另一個def clean_password()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM