【发布时间】:2015-05-29 19:25:56
【问题描述】:
我正在使用内置的用户模型在我的应用程序中存储用户信息。 但是,在注册新用户时,我希望用户名应该是唯一的。为此,我决定在我的模型表单中覆盖 clean_username 方法。这是我的 forms.py 文件
from django import forms
from django.contrib.auth.models import User
class Registration_Form(forms.ModelForm):
password=forms.CharField(widget=forms.PasswordInput())
class Meta:
model=User
fields=['first_name', 'last_name', 'username', 'email', 'password']
def clean_username(self):
value=self.cleaned_data['username']
if User.objects.filter(username=value[0]):
raise ValidationError(u'The username %s is already taken' %value)
return value
这是我的views.py文件
from django.shortcuts import render
from django.shortcuts import redirect
# Create your views here.
from django.contrib.auth.models import User
from registration.forms import Registration_Form
def register(request):
if request.method=="POST":
form=Registration_Form(request.POST)
if form.is_valid():
unm=form.cleaned_data('username')
pss=form.cleaned_data('password')
fnm=form.cleaned_data('first_name')
lnm=form.cleaned_data('last_name')
eml=form.cleaned_data('email')
u=User.objects.create_user(username=unm, password=pss, email=eml, first_name=fnm, last_name=lnm)
u.save()
return render(request,'success_register.html',{'u':u})
else:
form=Registration_Form()
return render(request,'register_user.html',{'form':form})
但是在单击表单的提交按钮时出现此错误
异常类型:TypeError
异常值:
'dict' 对象不可调用
异常位置:/home/srai/project_x/registration/views.py 在寄存器中,第 12 行
有问题的行是这样的
unm=form.cleaned_data('用户名')
谁能告诉我为什么会出现这个错误以及如何解决它。 谢谢。
【问题讨论】:
标签: python django django-forms django-validation