django modelform清洁

时间:2009-12-18 15:28:15

标签: django django-forms

我发现了一些与此类似的帖子,但它们并没有100%明确,所以这里有:

在我的观看中,我有一个add_album视图,允许用户上传相册。我想做的是清理表单(AlbumForm)以检查此专辑是否对艺术家来说是唯一的。

我的AlbumForm看起来像这样:

class AlbumForm(ModelForm):
  class Meta:
    model = Album
    exclude = ('slug','artist','created','is_valid', 'url', 'user', 'reported')

  def clean_name(self):
    super(AlbumForm, self).clean()
    cd = self.cleaned_data
    try:
      Album.objects.get(slug=slugify(cd['name']), artist=artist)
      raise forms.ValidationError("Looks like an album by that name already exists for this artist.")
    except Album.DoesNotExist:
      pass

    return cd

这就是我想要做的事情。

我的问题是:有没有办法将artist对象从我的视图传递到表单,以便我可以在artist方法中使用该clean实例?

我认为我正在考虑覆盖__init__的{​​{1}}方法,但我不确定如何做到这一点。

1 个答案:

答案 0 :(得分:4)

更好的方法是在模型级别,使用内置的Meta选项unique_together

如果你有一个模型Album,那么你可以这样做:

def Album(models.Model):
   ...

   class Meta:
     unique_together = ("artist_id", "title")
相关问题