Django表单“软”验证,发回用户以明确确认可疑数据

时间:2018-11-01 13:50:54

标签: django django-forms

我有一个整数字段,其形式必须在100到1000之间。但是,如果输入的值不是100、200、381(不要问),525或1000,则它是很可能这是错误的。

我想做的就是我所谓的“软验证”-我不知道是否有任何标准术语。第一次,该表格会引发错误,然后“确认?”将会添加布尔字段,默认为{ # ... 0x41: '\u0950', # ... } 。如果再次返回带有确认字段false的消息,则将无法接受数据。

答案Warnings (or even info messages) instead of only errors in Django显示了如何使用逐字段和逐表单添加的自定义代码来完成此操作-但我宁愿不这样做。有人知道开放源码中是否已经以通用,可重用的方式完成了此任务?在我的梦里,我会true(不存在),其余的会照顾自己。

我不知道要用Google搜索什么。我在https://djangopackages.org/

上找不到任何明显的内容

1 个答案:

答案 0 :(得分:0)

在这里您找到了一个最小的工作示例,类似于注释链接中给出的示例。您只需要小心不要在clean_MagicNumber(self)函数中包括软验证-这很容易出现争用情况,因为只设置了clean_data属性。 而是使用覆盖的clean(self)validate_unique(self)函数。

from django.core.exceptions import ValidationError
from django.db import models
from django.contrib import admin
from django import forms
from django.db import models


class Autor(models.Model):
    Name = models.CharField(max_length=64)
    MagicNumber = models.IntegerField()


class AutorAdminForm(forms.ModelForm):
    ConfirmMagicNumber = forms.BooleanField(label="I confirm it is the right magic number.",
                                            required=False,
                                            widget=forms.HiddenInput)

    def _field_is_active(self, field):
        if self._meta.exclude is not None and field in self._meta.exclude:
            return False
        if self._meta.fields is not None and field in self._meta.fields:
            return True
        return False

    def clean_MagicNumber(self):
        if self.cleaned_data['MagicNumber'] < 100 or self.cleaned_data['MagicNumber'] > 1000:
            raise ValidationError("Magic number outside of allowed range between 100 to 1000.")
        return self.cleaned_data['MagicNumber']

    def validate_unique(self):
        """
            We use validate unique because it is quite late in the validation process,
            after we got the values of all fields and
            actually I used it, because I was really warning for a possible duplicate
        """
        super().validate_unique()
        # only check if number does not have errors and is in form data
        if 'MagicNumber' not in self._errors and 'MagicNumber':
            # only check if confirm checkbox is given and not checked
            if ('ConfirmMagicNumber' in self.cleaned_data and 'ConfirmMagicNumber' in self.fields
                and self.cleaned_data['ConfirmMagicNumber'] is not True and self._field_is_active('ConfirmMagicNumber')):
                    if self.cleaned_data['MagicNumber'] not in (100, 200, 381, 525, 1000):
                        error_msg = "The magic number looks wrong. Please confirm it below."
                        self.add_error('MagicNumber', error_msg)
                        self.fields['ConfirmMagicNumber'].widget = forms.CheckboxInput()
                        self.fields['ConfirmMagicNumber'].required = True

@admin.register(Autor)
class AutorAdmin(admin.ModelAdmin):
    form = AutorAdminForm