开发者

django modelform clean

I've found a few posts that are similar in nature to this but they haven't been 100% clear so here goes:

In my views I have an add_album view that allows a user to upload an album. What I'd like to do is clean the form (AlbumForm) to check if this album is unique for an artist.

My AlbumForm looks like this:

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

  def clean_name(self):
    super(AlbumFo开发者_运维问答rm, 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

So that's something along the lines of what I'd like to do.

My questions is: is there a way to pass the artist object from my view to the form so I can use that artist instance in the clean method?

I think I am looking at overriding the __init__ method of the ModelForm, but I am unsure how to do it.


A better way to do this is at the model level, with the built-in Meta option, unique_together.

If you've got a model Album, then you can probably do something like this:

def Album(models.Model):
   ...

   class Meta:
     unique_together = ("artist_id", "title")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜