代码之家  ›  专栏  ›  技术社区  ›  nigel222

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

  •  0
  • nigel222  · 技术社区  · 6 年前

    很可能 这是错误的。

    false . 如果再次返回确认字段 true ,则不太可能的数据将被接受。

    Warnings (or even info messages) instead of only errors in Django 演示了如何通过逐个字段和逐个表单添加自定义代码来实现这一点,但我不想这样做。有人知道这是否已经在开源代码中以一种通用的、可重用的方式实现了吗?在我的梦里,我会 raise ValidationWarning ... (它不存在)剩下的会自己照顾自己。

    https://djangopackages.org/

    0 回复  |  直到 6 年前
        1
  •  0
  •   Kound    5 年前

    在这里,您可以找到一个与注释中的链接中给出的示例类似的最小工作示例。您只需小心不要将软验证包括在 clean_MagicNumber(self) 而是使用覆盖的 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