简单的形式没有验证

时间:2010-07-05 21:29:31

标签: django django-forms validation django-signals django-registration

我在stackoverflow上找到了一种使用信号扩展django内置身份验证的方法。我的基本用户由'email'和密码定义(因此没有用户名)。所以我试图根据我的需要修改它,但我正在为我的表单设置验证错误。奇怪的是,错误已连接到User.email字段,即使我刚刚注册,我也已“正在使用”。是试图保存2次还是什么?当我发送带有数据的字典以形成shell中的contstructor时,我发现了它: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',)

报名表: class 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

2 个答案:

答案 0 :(得分:1)

保存用户后发送'user_registered'信号。所以它已经定义了一个“电子邮件”字段。

<强>更新


使用不安的思维:

form = CustomRegistrationForm(request.POST, request.FILES, notvalidateemail=True)

并以表格形式:

def __init__(self, *args, **kwargs):
    self.notvalidateemail = kwargs.pop('notvalidateemail',False)
    super(CustomRegistrationForm, self).__init__(*args, **kwargs)

def clean_email(self):
    if self.notvalidateemail:
        return
    else:
        #your cleaning here
        return email

答案 1 :(得分:0)

问题:

您的表单首先由django-registration保存。然后再将其保存在user_created中。

解决方案:

  1. 在user_created中使用其他表单。一个不会保存字段的字段(这些来自用户模型,如电子邮件)。您只想在user_created中保存其他数据,对吧?

  2. 向表单添加一些参数,如:

  3. 在user_created中

    form = CustomRegistrationForm(dontvalidateemail=True, request.POST, request.FILES)
    

    并以表格的 init ;

    self.dontvalidateemail = dontvalidateemail
    

    然后只需在clean_email中查看。