简体   繁体   中英

Django Admin: Limit query-set selection for a inline form

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,
    ]

You need to save a copy of the Place object that the parent form is updating, and use that object as a clue to limit the choices of Photo form field of the inline forms.

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

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):

        formfield = super(Photoinline, self).formfield_for_foreignkey(db_field, request, **kwargs)
        if db_field.name == 'photo':
            if request._place_obj is not None:
                formfield.queryset = formfield.queryset.filter(place__exact = request._place_obj)
            else:
                formfield.queryset = formfield.queryset.none()
        return formfield

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,
    ]

    def get_form(self, request, obj=None, **kwargs):
        request._place_obj = obj
        return super(PlaceAdmin, self).get_form(request, obj, **kwargs)

This answer may help you know more about the details: https://stackoverflow.com/a/4236159/11326730

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM