如何验证Django中卖家模型中的唯一手机号码

时间:2017-02-19 17:50:16

标签: django django-models django-forms django-validation

我正在尝试验证模特卖家的mobileno(独特)。 但它给了我错误而没有做任何期望的任务 我该怎么做才能在表格中检查mobileno的唯一性?
以下是我的model.py:

    class Seller(models.Model):
    mobilenno = models.DecimalField(max_digits=10, decimal_places=0, unique=True)  # Field name made lowercase.
    password = models.CharField(max_length=64)
    name = models.CharField( max_length=64)
  #  city = models.ForeignKey(City)
    address = models.CharField(max_length=512, blank=True, null=True)  # Field name made lowercase.
    phoneno = models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True)  # Field name made lowercase.

和form.py

class SellerRegistrationForm(forms.Form):

    mobileno1 = forms.DecimalField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)),
                                  max_digits=10, decimal_places=0,label=_("Mobile Number"))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)),
                                label=_("Password"))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)),
                                label=_("Password (again)"))
    name = forms.CharField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)),
                                 label=_("Seller Name"))
    address = forms.CharField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)),
                                 label=_("Seller Address"))
    phoneno = forms.DecimalField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)),
                                 max_digits=10, decimal_places=0, label=_("Phone Number"))

    def clean_mobileno1(self):

        try:
            Seller.objects.get(mobileno=self.cleaned_data['mobileno1'])
        except Seller.DoesNotExist:
            return self.cleaned_data['mobileno1']
        raise forms.ValidationError(_("The mobilenumber already exists. Please try another one."))

    def clean(self):
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(_("The two password fields did not match."))
        return self.cleaned_data

views.py

def seller_register(request):
    if request.method == 'POST':
        form = SellerRegistrationForm(request.POST)
        if form.is_valid():
            Seller.objects.create(
                mobilenno=form.cleaned_data['mobileno1'],
                password=form.cleaned_data['password1'],
                name=form.cleaned_data['name'],
                address=form.cleaned_data['address'],
                phoneno=form.cleaned_data['phoneno']
            )
            return HttpResponseRedirect('/register/success/')
    else:
        form = SellerRegistrationForm()

    return render(request,'registration/register.html', {'form': form })

1 个答案:

答案 0 :(得分:0)

我不清楚你得到了什么错误,所以我不确定错误在哪里,但clean_mobileno1看起来是个好人选。检查mobilennomobileno1之间的命名一致性。

该函数中的逻辑难以理解,您尝试捕获" normal"的异常。用例,如果你没有抓住第一个,那么就引发异常,这似乎是反直觉的。此外,您正在检查python中的unicity,当它真的应该被推送到数据库时(字段定义中的unique=True应该强制执行)。

我建议您使用https://github.com/stefanfoulis/django-phonenumber-field代替Decimal电话号码。您将获得实际的电话号码验证,以及一系列非常有用的电话特定功能。后端基于Android的电话号码库,因此它可以保持最新状态。

您的模型变为:

from phonenumber_field.modelfields import PhoneNumberField

class Seller(models.Model):
    mobileno = PhoneNumberField(unique=True)
    ...

此外,您应该使用ModelForm表单:

class SellerRegistrationForm(forms.ModelForm):
    class Meta:
        model = Seller

    ...