views:

347

answers:

2

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(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

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.

+3  A: 

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")
Dominic Rodger
I'm trying this but it doesn't seem to work. My "artist" field is a ForeignKey to an Artist model. So I do: unique_together = ('artist', 'slug') -- not 100% on how this is supposed to work.
tsoporan
Try `unique_together = ("artist_id", "slug")`. Not completely sure whether `unique_together` works with ForeignKeys.
Dominic Rodger
Oh hey silly me, I forgot this was a database level change (didn't run migrations). It's working, thanks, this is a lot better.
tsoporan
A: 

Just wondering here - how would we pass the Artist down from the view to the form if we needed to?

harry