简体   繁体   中英

Django admin inline conditional values

I am creating a inline form in the Django admin that is suppose to have conditional values.

For example, I have this models

class Category (models.Model):
    name = models.CharField(max_length=500)
    parent = models.ForeignKey('self', blank=True, null=True, related_name='subcategory')
    def __unicode__(self):
        return self.name

class Business(models.Model):
    category = models.ForeignKey(Category)
    name = models.CharField(max_length=500)
    def __unicode__(self):
        return self.name


class DescriptionType (models.Model):
    category = models.ManyToManyField(Category)
    name = models.CharField(max_length=500)
    def __unicode__(self):
        return self.name


class Descriptions (models.Model):
    descriptiontype = models.ForeignKey(DescriptionType)
    business = models.ForeignKey(Business)

So, I have a Category ("Restaurants"), and DescriptionType ("Food Speciality", which belong only to "Restaurants").

So I want to create the Business "Foster Hollywood" with is category "restaurant" and I would like in the admin inline DescriptionsInline allow only to select the DescriptionTypes that belongs to the category "restaurant". My current solution displays all the values of Description Types

class DescriptionsInline(admin.TabularInline):
    model = Descriptions
    extra = 0

class BusinessAdmin(admin.ModelAdmin):
    inlines = [DescriptionsInline]
    list_display = ('name',)
    search_fields = ['name']

admin.site.register(Business, BusinessAdmin)

how could I make for the inline DescriptionsInline display only the DescriptionTypes from the selected category for the Business ?

I found a solution at http://www.stereoplex.com/blog/filtering-dropdown-lists-in-the-django-admin

class DescriptionsInline(admin.TabularInline):
    model = Descriptions
    exclude = ['modified']
    extra = 0
    def formfield_for_dbfield(self, field, **kwargs):
        if field.name == 'descriptiontype':
            parent_business = self.get_object(kwargs['request'], Business)
            if parent_business == None:
                related_descriptiontype = DescriptionType.objects.all()
            else:
                related_descriptiontype = DescriptionType.objects.filter(category=parent_business.category_id)
            return forms.ModelChoiceField(queryset=related_descriptiontype)
        return super(DescriptionsInline, self).formfield_for_dbfield(field, **kwargs)


    def get_object(self, request, model):
        object_id = request.META['PATH_INFO'].strip('/').split('/')[-1]
        try:
            object_id = int(object_id)
        except ValueError:
            return None
        return model.objects.get(pk=object_id)

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