python - Django admin inline conditional values -


i creating inline form in django admin suppose have conditional values.

for example, have 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, have category ("restaurants"), , descriptiontype ("food speciality", belong "restaurants").

so want create business "foster hollywood" category "restaurant" , in admin inline descriptionsinline allow select descriptiontypes belongs category "restaurant". current solution displays values of description types

class descriptionsinline(admin.tabularinline):     model = descriptions     = 0  class businessadmin(admin.modeladmin):     inlines = [descriptionsinline]     list_display = ('name',)     search_fields = ['name']  admin.site.register(business, businessadmin) 

how make inline descriptionsinline display descriptiontypes selected category business ?

i found solution @ http://www.stereoplex.com/blog/filtering-dropdown-lists-in-the-django-admin

class descriptionsinline(admin.tabularinline):     model = descriptions     exclude = ['modified']     = 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) 

Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -