我有两个模特:
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)我有一个电影表单,允许用户选择一个预先存在的工作室,或者键入一个新的工作室(在先前的问题的帮助下)
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:无法赋值:" Film.studio“不允许空值错误。我以为我捕获了所有的错误,因此django永远不应该知道Film.studio是空的。
第二个问题是操作顺序。如果我只想在确定其余的是有效的(从而防止在完整的电影条目通过之前保存一堆工作室名称)保存new_studio怎么办?是空的,还是因为new_ FilmForm被保存在表单的清理中而冒着过早保存的风险?
编辑:添加 回溯 并编辑验证if-语句
发布于 2012-01-26 00:49:44
从studio和new_studio中删除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!")发布于 2012-01-26 03:27:59
关于防止预制滥调new_studio:
新的def清洁(自我):cleaned_data = self.cleaned_data studio = cleaned_data.get('studio') new_studio = cleaned_data.get('new_studio')
    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!")
    elif not studio:
        del cleaned_data['studio']
    return super(FilmForm,self).clean()并认为:
def testone(request):
    if request.method == 'POST': # If the form has been submitted...
        form = FilmForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            if form.cleaned_data['new_studio']:
                studio, created = Studio.objects.get_or_create(name = form.cleaned_data['new_studio'])
                new_film = form.save(commit=False)
                new_film.studio = studio
            else:
                new_film = form
            new_film.save()
            return HttpResponseRedirect('/') # Redirect after POST
        else:
            form = FilmForm() # An unbound form
        return render_to_response('testone.html', {
            'form': form
        }, context_instance=RequestContext(request))https://stackoverflow.com/questions/9010852
复制相似问题