I have a model for adding entries of Mobile apps:
class MobileApp(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
images = models.ManyToManyField(Image, blank=True)
In Django Admin, what i am trying to do is filter the images that are listed in the list to prevent django from loading all images in that table which are quite alot.
So what i currently do is the following:
class MobileAppAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super(MobileAppAdmin, self).get_form(request, obj, **kwargs)
if obj:
form.base_fields['images'].queryset = Image.objects.filter(pk__in=obj.images.all())
else:
form.base_fields['images'].queryset = Image.objects.filter(pk=0)
return form
But when submitting the form, adding a new image, what happens is the following:
Select a valid choice. XYZ is not one of the available choices.
On the images field.
How can i make this work? i have lots of fields that need the same move as django keeps loading all the records to populate the lists for relations.
Thanks
Don't limit options when form being submitted.
class MobileAppAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super(MobileAppAdmin, self).get_form(request, obj, **kwargs)
if request.method == 'GET':
if obj:
form.base_fields['images'].queryset = Image.objects.filter(pk__in=obj.images.all())
else:
form.base_fields['images'].queryset = Image.objects.filter(pk=0)
return form
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With