我在這裏找到了一個使用信號擴展django內置認證的方法。我的基本用戶由'email'和密碼定義(所以沒有用戶名)。所以我試圖修改它以滿足我的需求,但是我爲表單創建了一個驗證錯誤。奇怪的是,這個錯誤與User.email字段有關,即使我現在正在註冊,我也正在'已經在使用'。它試圖保存2次還是什麼?當我發送包含數據的字典以形成shell的結果時,我發現它:form = MyForm(data={})
。在這個表格仍然無效後,但是將電子郵件改爲不同的值最終給了我真實的。簡單的表單無法驗證
的user_created功能連接到登記信號:
def user_created(sender, user, request, **kwargs):
form = CustomRegistrationForm(request.POST, request.FILES)
if form.is_valid():
data = UserProfile(user=user)
data.is_active = False
data.first_name = form.cleaned_data['first_name']
data.last_name = form.cleaned_data['last_name']
data.street = form.cleaned_data['street']
data.city = form.cleaned_data['city']
data.save()
else:
return render_to_response('user/data_operations/error.html', {'errors': form._errors}, context_instance=RequestContext(request))
user_registered.connect(user_created)
我的形式:
class CustomRegistrationForm(RegistrationForm):
first_name = forms.CharField(widget=forms.TextInput(attrs=attrs_dict), max_length=50)
last_name = forms.CharField(widget=forms.TextInput(attrs=attrs_dict), max_length=50)
street = forms.CharField(widget=forms.TextInput(attrs=attrs_dict), max_length=50)
city = forms.CharField(widget=forms.TextInput(attrs=attrs_dict), max_length=50)
我的模型:
class UserProfile(models.Model):
first_name = models.CharField(_("Name"), max_length=50, blank=False,)
last_name = models.CharField(_("Last name"), max_length=50, blank=False,)
street = models.CharField(_("Street"), max_length=50, blank=False,)
city = models.CharField(_("City"), max_length=50, blank=False,)
user = models.ForeignKey(User, unique=True, related_name='profile',)
登記表格: 類RegistrationForm(forms.Form) :
email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
maxlength=75)),
label=_("Adres email"))
password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
label=_("Haslo"))
password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
label=_("Haslo powtorzone"))
def clean_email(self):
email = self.cleaned_data.get("email")
if email and User.objects.filter(email=email).count() > 0:
raise forms.ValidationError(
_(u"Already in use."))
return email
任何解決方法提示? – muntu 2010-07-06 19:36:10
編輯我的答案 – owca 2010-07-07 03:46:22