Django UserChangeForm自定义验证

时间:2018-10-11 07:07:15

标签: django django-forms

ValueError:由于数据无效,无法更改Custom_User。

我正在尝试制作一个UserChangeForm以允许客户编辑其地址,联系人或密码。但是,对于“ 邮政编码”字段,我设置了一个限制,即只有某些我要提供的邮政地址。

#forms.py
#Extract list of postal codes which are valid and put into a list
valid_postal_code = []
postal_code_model = PostalCode.objects.all()
for code in postal_code_model:
    valid_postal_code.append(code.postal_code)

#form
class EditAccountForm(UserChangeForm):
    class Meta:
        model = Custom_User
        fields = (
            'address',
            'postal_code',
            'unit_number',
            'email',
            'contact_number',
            'password'          
            )
    def clean_postal_code(self):
        post_code = self.cleaned_data.get('postal_code')
        if post_code not in valid_postal_code:
            print('hello')
            raise forms.ValidationError('Sorry we do not serve this postal code right now D:')
        return post_code

如果用户输入的邮政编码不在 valid_postal_code列表中,则我希望该表单能够在表单上引发错误消息。 但是,我立即得到上述错误(这是可以预期的),而没有引发错误。

#views.py
def edit_info_page(request):

    if request.method == 'POST':
        form = EditAccountForm(request.POST, instance=request.user)
        if form.is_valid:
            form.save()
            print('form changed')
            return redirect('home:edit_info_page')
    else:
        form = EditAccountForm(instance=request.user)
    return render(request, 'sign/edit_info.html', {'form':form})


#models
class Custom_User(AbstractUser):
    postal_code = models.IntegerField(null=True)
    unit_number = models.CharField(max_length=10)
    address = models.CharField(max_length=250)
    contact_number = models.IntegerField(null=True)
    order_count = models.PositiveIntegerField(default=0)
    total_spending = models.DecimalField(max_digits=10, decimal_places=2, default=0)


    def __str__(self):
        return self.username

以上是我的模型和观点供参考。 IMO,我想我肯定是在这里遗漏了一些东西,但是我不太确定如何闯入UserChangeForm。我还是一个相对较新手(尚未将任何东西发送到生产环境中)。任何建议都会很棒!

2 个答案:

答案 0 :(得分:0)

尝试一下

class EditAccountForm(UserChangeForm):
class Meta:
    model = Custom_User
    fields = (
        'address',
        'postal_code',
        'unit_number',
        'email',
        'contact_number',
        'password'          
        )
def clean_postal_code(self):
valid_postal_code = PostalCode.objects.all().values_list('postal_code', flat=True)
    post_code = self.cleaned_data.get('postal_code')
    if post_code not in valid_postal_code:
        raise forms.ValidationError('Sorry we do not serve this postal code right now D:')
    return post_code

一种更好的方式来编写postal_code字段的AJAX调用,并从postal_code焦点输出/模糊事件调用ajax函数, 或者使邮政编码字段自动填写或选择字段

答案 1 :(得分:0)

在视图中进行更改:

if form.is_valid:

if form.is_valid():

验证未执行,因此不验证您的帖子数据,从而又不允许您保存用户。

建议:

更改
if post_code not in valid_postal_code:

if post_code and post_code not in valid_postal_code:

确保仅在用户输入内容时引发错误。