I have a Django admin form with an inline form as follows. It has many to many field. models Place
has photos = models.ManyToManyField(Photo)
, and Photo
is another Django model.
The trouble is that I have too many instances of Photo
, click I edit the form under Django admin, I get a dropdown with all the Photo instance selection.
How can I limit the selections that only has a relationship with Place
?
class Photoinline(admin.TabularInline):
model = Place.photos.through
extra = 1
readonly_fields = ('preview', 'my_order',)
def preview(self, obj):
if obj.photo:
id = obj.photo_id
photo = Photo.objects.get(id=id)
return mark_safe('<img src="/media/%s" width="150" />' % (photo.photo))
else:
return mark_safe('Empty, please upload an image')
def my_order(self, obj):
id = obj.photo_id
photo = Photo.objects.get(id=id)
if not photo.order:
return ""
return photo.order
class PlaceAdmin(admin.ModelAdmin):
list_display = ('name', 'city', 'state', 'country')
exclude = ('photos',)
formfield_overrides = {
models.ForeignKey: {'widget': Select(attrs={'style':'width: 350px;'})},
models.FloatField: {'widget': Select(attrs={'style':'min-width: 350px;'})},
models.URLField: {'widget': TextInput(attrs={'style':'width: 350px;'})},
models.CharField: {'widget': TextInput(attrs={'style':'width: 350px;'})},
models.TextField: {'widget': Textarea(attrs={'style':'width: 350px;height: 38px;'})}
}
inlines = [
Photoinline,
]