在django表单中捕获验证错误 [英] Catching validation errors in django forms

查看:141
本文介绍了在django表单中捕获验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型:

class Studio(models.Model):
    name = models.CharField("Studio", max_length=30, unique=True)

class Film(models.Model):
    studio = models.ForeignKey(Studio, verbose_name="Studio")
    name = models.CharField("Film Name", max_length=30, unique=True)

一个电影表单,允许用户选择一个预先存在的工作室,或输入一个新的(借助于早期问题

I have a Film form that allows the user to either select a preexisting Studio, or type in a new one (with help from an earlier question:

class FilmForm(forms.ModelForm):
    required_css_class = 'required'
    studio = forms.ModelChoiceField(Studio.objects, required=False, widget = SelectWithPlus)
    new_studio = forms.CharField(max_length=30, required=False, label = "New Studio Name", widget = DeSelectWithX(attrs={'class' : 'hidden_studio_field'}))

    def __init__(self, *args, **kwargs):
        super(FilmForm, self).__init__(*args,**kwargs)
        self.fields['studio'].required = False

    def clean(self):
        cleaned_data = self.cleaned_data
        studio = cleaned_data.get('studio')
        new_studio = cleaned_data.get('new_studio')

        if not studio and not new_studio:
            raise forms.ValidationError("Must specify either Studio or New Studio!")
        elif not studio:
            studio, created = Studio.objects.get_or_create(name = new_studio)
            self.cleaned_data['studio'] = studio

        return super(FilmForm,self).clean()

    class Meta:
        model = Film

现在,我的第一个问题是,当studio和new_studio都缺少我得到一个django ValueError:不能指定None:Film.studio不允许空值错误。我以为我正在捕获所有错误,所以django永远不应该到达实现Film.studio是空的。

Now, my first issue is that when both studio and new_studio are missing I get a django ValueError: Cannot assign None: "Film.studio" does not allow null values error. I thought I was capturing all the errors, thus django should never get so far as to realize Film.studio is empty.

第二个问题是操作顺序。 如果我想要保存MovieForm的其余部分后才能保存new_studio怎样才能保存(从而防止在完整的电影录像通过之前保存一堆录音室名称)?我是在清除或者是否冒险提前保存,因为new_studio被保存在表单的清理中?

A second issue is an order of operations. What if I want to only save the new_studio after I'm sure the rest of the FilmForm is valid (thus preventing a bunch of studio names getting saved before full Film entries go through as well)? Am I in the clear or do I risk premature saving because new_studio's are saved in the form's cleaning?

编辑:添加追溯并编辑验证if-statements

Added Traceback and edited validation if-statements

推荐答案

从clean_data删除工作室 new_studio

Delete studio and new_studio from cleaned_data.

    if not studio and not new_studio:
        del cleaned_data['studio'], cleaned_data['new_studio']
        raise forms.ValidationError("Must specify either Studio or New Studio!")

这篇关于在django表单中捕获验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆