I've got a couple django models that look like this:
from django.contrib.sites.models import Site
class Photo(models.Model):
title = models.CharField(max_length=100)
site = models.ForeignKey(Site)
file = models.ImageField(upload_to=get_site_profile_path)
def __unicode__(self):
return self.title
class Gallery(models.Model):
name = models.CharField(max_length=40)
site = models.ForeignKey(Site)
photos = models.ManyToManyField(Photo, limit_choices_to = {'site':name} )
def __unicode__(self):
return self.name
I'm having all kinds of fun trying to get the limit_choices_to
working on the Gallery model. I only want the Admin to show choices for photos that belong to the same site as this gallery. Is this possible?
According to the docs, "limit_choices_to has no effect when used on a ManyToManyField with an intermediate table". By my reading, that means it has no effect at all, because ManyToManyFields use intermediate tables...
I haven't tried to make it work in the Admin site, but from your own views, you can create a form and override the queryset used to populate the list of choices:
Yes. You need to override the form that admin uses for the
Gallery
model, then limit the queryset of thephotos
field in that form:I would delete
site
field on myPhoto
model and add aForeignKey
toGallery
. I would removelimit_choices_to
fromphotos
fields onGallery
model.Because you are using
ForeignKey
s toSite
s, that means sites don't share galleries and photos. Therefore having those I mentioned above is already useless.Once you set the
site
on a gallery all its photos will inherit this property. And the site will be accessible asphoto_instance.gallery.site
:This should work as if you had a
site
field. But I haven't tested it.Things change or course, if you decide that a gallery or a photo can appear in multiple sites.