【问题标题】:ValidationError raises when updating更新时引发 ValidationError
【发布时间】:2017-03-13 10:31:33
【问题描述】:

我定义了一个ValidationError。它工作正常,但是当我尝试更新我的表单时,它会引发。因此,我无法再更新我的表格了。定义如下:

def clean_examination(self):
    new_exa = self.cleaned_data.get('examination')
    try:
        old_exa=GeneralData.objects.get(examination=self.cleaned_data.get('examination'))
    except GeneralData.DoesNotExist:
        return new_exa
    if old_exa:
        raise forms.ValidationError('Object with this examination already exists!')
    return new_exa`

如果要更新表单,是否可以“停用”我的ValidationError

附加信息: 我的模特:

class GeneralData(models.Model):
    examination = models.ForeignKey(Examination, on_delete=models.CASCADE, help_text='This value is pasted in automatically and is not editable!')
    attr1= models.FloatField()
    attr2= models.FloatField()

我的更新视图:

class GeneralDataUpdate(LoginRequiredMixin, generic.UpdateView):
    model = GeneralData
    form_class = GeneralDataCreateForm
    template_name_suffix = '_update_form'
    login_url = 'member:login'

    def get_success_url(self):
        return reverse('member:detail', kwargs={'pk': self.get_object().examination.patient_id})

    def get_context_data(self, **kwargs):
        context = super(GeneralDataUpdate, self).get_context_data(**kwargs)
        context['action'] = reverse('member:generaldata-update',
                                     kwargs={'pk': self.get_object().id})
        return context

我的更新网址:

url(r'examination/(?P<pk>[0-9]+)/generaldata/update/$', views.GeneralDataUpdate.as_view(), name='generaldata-update')

【问题讨论】:

    标签: django django-forms django-validation


    【解决方案1】:

    如果您的表单来自ModelForm 类型,则您有一个属性self.instance。然后您可以检查是否设置了self.instance.id,并处理您的验证。

    if self.instance.id:
        # raise ValidationError
    

    如果你不使用它,应该清理 id,它应该与请求一起发送。如果存在则抛出ValidationError,或者继续..

    id = self.cleaned_data.get('id', None)
    if id:
         # raise ValidationError
    

    例子:

    def clean_examination(self):
        new_exa = self.cleaned_data.get('examination')
        try:
            old_exa = GeneralData.objects.get(
                examination=self.cleaned_data.get('examination'))
        except GeneralData.DoesNotExist:
            return new_exa
    
        if old_exa:
            if not self.instance.id:
                raise forms.ValidationError(
                    'Object with this examination already exists!')
        return new_exa
    

    在这种情况下,ValidationError 只有在没有旧对象的情况下才会在有旧的examination 时引发。

    请注意,如果对象具有id,则更改为已存在的名称为 OTHER id,您将拥有两个具有相同检查的不同对象。不确定这是否可以,但这当然取决于您。

    【讨论】:

      猜你喜欢
      • 2019-01-26
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      相关资源
      最近更新 更多