我只是为用户注册创建一个表单 代码在这里
forms.py
from django import forms
from django.conf import settings
from django.contrib.auth import get_user_model
def lowercase_email(email):
"""
Normalize the address by lowercasing the domain part of the email
address.
"""
email = email or ''
try:
email_name, domain_part = email.strip().rsplit('@', 1)
except ValueError:
pass
else:
email = '@'.join([email_name.lower(), domain_part.lower()])
return email
class SignupForm (forms.ModelForm):
username =forms.CharField(
label='username',required=True,max_length=20,min_length=3)
email = forms.EmailField(
label='email',required=True)
password =forms.CharField(
label='pssword',required=True,max_length=20,min_length=6,widget = forms.PasswordInput)
confirm_password= forms.CharField(
label='confirm_email',required=True,max_length=20,min_length=6,widget = forms.PasswordInput)
class Meta:
model = get_user_model()
fields = ("username","email","password","confirm_password",)
def clean(self):
password = self.cleaned_data["password"]
confirm_password = self.cleaned_data["confirm_password"]
if password and password != confirm_password:
raise forms.ValidationError("password not same")
return password
和views.py
from django.shortcuts import render_to_response, redirect,render
from django.conf import settings
from django.http import HttpResponse,HttpResponseRedirect,Http404
from django.template import RequestContext
from sns.accounts.forms import SignupForm
from django.contrib.auth import get_user_model
def signup(request):
if request.method=='POST':
form=SignupForm(data=request.POST)
if form.is_valid():
UserModel=get_user_model()
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user=UserModel.objects.create_user(username=username,email=email,password=password)
return redirect('/')
else:
form=SignupForm(auto_id=True)
return render_to_response('signup.html',{'form':form},context_instance=RequestContext(request))
一旦我测试它,就会显示错误
'str' object has no attribute 'get'
然后我从forms.py中删除方法clean,然后一切正常
我不知道问题出在哪里。因为我刚刚为其他人编写了相同的代码来处理干净的方法。
答案 0 :(得分:5)
看起来你在clean()的开头就错过了对super的clean()的调用。
cleaned_data = super(SignupForm, self).clean()
错误消息似乎表明cleaning_data是一个字符串而不是字典;它可能有助于打印cleaning_data以查看它是什么。
答案 1 :(得分:4)
将clean(self)
更改为clean_confirm_password(self)
或
为cleaned_data
返回def clean(self)
因为干净的def需要一个字典,而你提供的是密码变量形式的字符串。