Django注册表单报错:TypeError: Field.__init__()意外收到参数'Label'
问题:Django注册表单报错 TypeError: Field.init() got an unexpected keyword argument 'Label'
报错栈
File "C:\Users\hitechlab\Desktop\mysite\home\urls.py", line 18, in from . import views File "C:\Users\hitechlab\Desktop\mysite\home\views.py", line 4, in from .forms import RegistrationForm File "C:\Users\hitechlab\Desktop\mysite\home\forms.py", line 9, in class RegistrationForm(forms.Form): File "C:\Users\hitechlab\Desktop\mysite\home\forms.py", line 10, in RegistrationForm username = forms.CharField(Label='Tài Khoản', max_length=30) File "C:\Users\hitechlab\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\fields.py", line 267, in __init__ super().__init__(**kwargs) TypeError: Field.__init__() got an unexpected keyword argument 'Label'
相关代码
urls.py
from unicodedata import name from django.urls import path from blog.models import Post from . import views urlpatterns = [ path('', views.list, name = 'blog'), path('<int:id>/', views.post, name = 'post'), ]
forms.py
import email from tkinter import Label, Widget from django import forms import re from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist class RegistrationForm(forms.Form): username = forms.CharField(Label='Tài Khoản', max_length=30) email = forms.EmailField(Label='Email') password1=forms.CharField(Label= 'Mật Khẩu', Widget = forms.PasswordInput()) password2=forms.CharField(Label= 'Nhập lại mật khẩu', Widget = forms.PasswordInput()) def clean_password2(self): if 'password1' in self.cleaned_data: password1= self.cleaned_data ['password1'] password2= self.cleaned_data ['password2'] if password1==password2 and password1: return password2 raise forms.ValidationError('Mật khẩu không hợp lệ') def clean_username (self): username= self.clean_data['username'] if not re.search(r'^\w+$',username): raise forms.ValidationError("Tên tài khoản có kí tự đặc biệt") try: User.objects.get(username=username) except ObjectDoesNotExist: return username raise forms.ValidationError('Tài Khoản không tồn tại') def save(self): User.objects.create_user(username=self.clean_data['username'], email=self.clean_data['email'], password= self.clean_data ['password1'])
解决方法
1. 修正字段参数名大小写
Django表单字段的参数名是小写的label和widget,你写成了大写的Label和Widget,这是报错的直接原因。
2. 修正方法缩进
clean_password2、clean_username、save方法需要缩进,作为RegistrationForm类的成员方法,否则会被当成全局函数,导致调用时出错。
3. 修正clean_data为cleaned_data
Django表单中获取清洗后的数据用的是self.cleaned_data,不是self.clean_data,这会导致运行时找不到属性的错误。
4. 移除不必要的导入
你导入了tkinter的Label和Widget,这和Django表单无关,应该删除,避免混淆。
修正后的forms.py代码
from django import forms import re from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist class RegistrationForm(forms.Form): username = forms.CharField(label='Tài Khoản', max_length=30) email = forms.EmailField(label='Email') password1 = forms.CharField(label='Mật Khẩu', widget=forms.PasswordInput()) password2 = forms.CharField(label='Nhập lại mật khẩu', widget=forms.PasswordInput()) def clean_password2(self): if 'password1' in self.cleaned_data: password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 == password2 and password1: return password2 raise forms.ValidationError('Mật khẩu không hợp lệ') def clean_username(self): username = self.cleaned_data['username'] if not re.search(r'^\w+$', username): raise forms.ValidationError("Tên tài khoản có kí tự đặc biệt") try: User.objects.get(username=username) except ObjectDoesNotExist: return username raise forms.ValidationError('Tài khoản đã tồn tại') # 修正原提示逻辑错误 def save(self): return User.objects.create_user( username=self.cleaned_data['username'], email=self.cleaned_data['email'], password=self.cleaned_data['password1'] )
另外注意:原clean_username中的错误提示逻辑有误,当查询到用户存在时,应该提示“Tài khoản đã tồn tại”(账号已存在),而不是“Tài Khoản không tồn tại”(账号不存在),已在修正后的代码中调整。
内容的提问来源于stack exchange,提问作者tommyte0
相关产品推荐
相关产品推荐

