0

我想为我的“添加电视节目表单”制作以下模板:一个标题字段和一个 tvshow_id 字段。用户可以在标题 CharField 中输入标题并使用 AJAX 按钮从我的数据库中检索匹配项。单击匹配后,将使用一些 jQuery 魔术填充 tvshow_id 字段。但是,如果不是,那也应该没问题,因为我的表单应该使用用户提供的标题字符串创建一个新的 tvshow 实例。

但是,我不断收到以下错误:

/tvshows/create/season/ 处的 ValueError

无法分配无:“Season.tvshow”不允许空值。

假设我有以下模型:

class Tvshow(models.Model):
    title = models.CharField(max_length = 255)

class Season(models.Model):
    tvshow = models.ForeignKey(Song)

这是我的表格。请注意,在我的表格中,我声明电视节目不是必需的,而根据我的模型,它是必需的。这是因为否则,该字段本身将引发 ValidationError。

class SeasonModelForm(models.ModelForm):
    tvshow = forms.CharField(required = False)

    def clean_season(self):
        tvshow_id = self.cleaned_data['tvshow']
        if tvshow_id:
            try:
                return Tvshow.objects.get(pk = tvshow_id)
            except Tvshow.DoesNotExist:
                raise forms.ValidationError("No tvshow with this ID was found.")
        else: return None

    def clean(self):
        """Assign a tvshow in case there is no Tvshow yet."""
        cd = self.cleaned_data
        if not isinstance(cd['tvshow'], Tvshow):
            try:
                cd['title']
            except KeyError:
                raise forms.ValidationError("Please provide at least a tvshow title.")
            else:
                cd['tvshow'] = Tvshow(title = cd['title'])
                cd['tvshow'].save()
        return cd

我的猜测是 Season.tvshow 的验证发生在我的代码运行之前的某个地方,但我似乎无法追踪它。

我会喜欢你的意见,在此先感谢。

4

2 回答 2

0

You need to return the value of tvshow_id from clean_season.

于 2012-08-18T15:34:55.000 回答
0

我设法通过clean_season()返回一个空Tvshow()实例来解决它,然后对clean(). 这不是我写过的最漂亮的代码,但它完成了工作。

def clean_season(self):
    """Must return a Song instance, whatever the cost."""
    tvshow_id = self.cleaned_data['tvshow']
    if tvshow_id:
        try:
            return Tvshow.objects.get(pk = tvshow_id)
        except Tvshow.DoesNotExist:
            raise forms.ValidationError("No tvshow with this ID was found.")
    else: return Tvshow()

def clean(self):
    """Create a tvshow in case there is no tvshow yet."""
    cd = super(SeasonMinimalModelForm, self).clean()
    if not cd['tvshow'].title:
        try:
            cd['title']
        except KeyError:
            raise forms.ValidationError("Please provide at least a title.")
        else:
            cd['tvshow'] = Tvshow(title = cd['title'])
            cd['tvshow'].save()
    return cd
于 2012-08-19T09:56:01.893 回答