filter by category the subcategories belonging to the same category of different products in the django admin area

Viewed 18

I want when am adding the products in the django admin, when I enter the category of the product to list only the subcategories belonging only to the category.

Here is my models

class Category(models.Model):
     category_name  = models.CharField(max_length=50)
     slug           = models.SlugField(max_length=100, unique=True)
     category_image      = models.ImageField(upload_to = 
     'photos/categories', blank = True)
     created_at     = models.DateTimeField(auto_now_add=True)




    class Sub_Category(models.Model):
        category           = models.ForeignKey(Category, on_delete=models.CASCADE)
        sub_category_name  = models.CharField(max_length=50)
        slug               = models.SlugField(max_length=100, unique=True)

In my admin area I want the subcategory to be filtered from the category when adding different products.... Like showing say Furniture(category) to show chairs, beds (subcategories)

class Product(models.Model):
    category         = models.ForeignKey(Category, on_delete=models.CASCADE)
    sub_category     = models.ForeignKey(Sub_Category, on_delete=models.CASCADE)
    product_name     = models.CharField(max_length = 200, unique=True)
    slug             = models.SlugField(max_length=200,  blank=True)
    description      = models.TextField(max_length = 1000)
    price            = models.IntegerField()
    discount_price   = models.IntegerField(blank=True)
    on_offer         = models.BooleanField(default=False)
1 Answers

Never used the admin as I like to do certain things on my own, so this will not be a complete answer, but it can help you in the right direction and perhaps someone else will show you how this applies to the django admin site.

The way to achieve this kind of functionality in general, is to use Javascript to fetch subcategories based on the selected category via an event trigger. There is no other way, because this is how the web works in a browser, you send a request and get a response, back and forth each time. If you pass the category and sub-category querysets to a form, automatically if you use forms.ModelForm, then you can create a view that serves you the sub-category based on category if you send its PK to its URL and filter on it, and then make a Javascript function to fetch this dynamically (without having to refresh the page or make a whole new request), perhaps also make the sub-category dropdown hidden or disabled until a category is selected and when you have recieved a response and then have replaced the content of the sub-category dropdown make it enabled or visible.

Related