【发布时间】:2018-03-20 13:09:37
【问题描述】:
填写注册表并点击提交后弹出此错误 “create_user() 接受 2 到 4 个位置参数,但给出了 6 个” 而且它不使用模板中的表单内的验证
不检查用户名或电子邮件是否已经在数据库中,甚至不检查密码是否匹配
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.forms.widgets import PasswordInput, TextInput
from django.core.exceptions import ValidationError
class CustomUserCreationForm(forms.Form):
username = forms.CharField(widget=TextInput(attrs={'class':'validate','id': 'icon_prefix', 'type': 'text'}), min_length=4, max_length=150)
email = forms.EmailField(widget=TextInput(attrs={'class':'validate','id': 'icon_prefix', 'type': 'text'}))
first_name = forms.CharField(widget=TextInput(attrs={'class':'validate','id': 'icon_prefix', 'type': 'text'}), min_length=2, max_length=150)
last_name = forms.CharField(widget=TextInput(attrs={'class':'validate','id': 'icon_prefix', 'type': 'text'}), min_length=2, max_length=150)
password1 = forms.CharField(widget=PasswordInput(attrs={'class':'validate','id': 'icon_prefix', 'type': 'password'}))
password2 = forms.CharField(widget=PasswordInput(attrs={'class':'validate','id': 'icon_prefix', 'type': 'password'}))
def clean_username(self):
username = self.cleaned_data['username'].lower()
r = User.objects.filter(username=username)
if r.count():
raise ValidationError("Username already exists")
return username
def clean_first_name(self):
first_name = self.cleaned_data['first_name']
return first_name
def clean_last_name(self):
last_name = self.cleaned_data['last_name']
return last_name
def clean_email(self):
email = self.cleaned_data['email'].lower()
r = User.objects.filter(email=email)
if r.count():
raise ValidationError("Email already exists")
return email
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise ValidationError("Password don't match")
return password2
def save(self, commit=True):
user = User.objects.create_user(
self.cleaned_data['username'],
self.cleaned_data['first_name'],
self.cleaned_data['last_name'],
self.cleaned_data['email'],
self.cleaned_data['password1']
)
return user
【问题讨论】:
-
你不应该使用positional arguments