Django按类别ID显示子类别

时间:2019-03-06 13:01:15

标签: python django categories

我认为URL和视图有问题。因此,我有3个类别,每个类别都有3个子类别。单击每个类别时,我想打开子类别。

urls.py:

urlpatterns = [
    path('', views.index),
    url(r'^category/(?P<pk>\d+)$', views.category, name='category'),
]

views.py:

def category(request):
    categories = Category.objects.all()
    subcategories = SubCategory.objects.all()
    return render(request, 'category.html', {'categories': categories, 'subcategories': subcategories}

base.html:

{% for category in categories%}
    <a class="dropdown-item" href="{% url 'category' pk=category.pk %}">{{ category.name }}</a>
{% endfor %}

models.py

class Category(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name


class SubCategory(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    image_url = models.CharField(default=0, max_length=2000)
    price = models.IntegerField(default=0)

1 个答案:

答案 0 :(得分:1)

urls.py

urlpatterns = [
    path('', views.index),
    url(r'^get_subcategory/(?P<pk>\d+)$', views.get_subcategory, name='get_subcategory'),
]

models.py(应该这样)

class Category():
     name=models.CharField()

class SubCategory():
     name=models.CharField()
     category = models.ForeignKey(Category)

views.py

def get_subcategory(request, pk):
        category = Category.objects.get(id=pk)
        subcategories = SubCategory.objects.filter(category=category)
        return render(request, 'category.html', {'categories': categories, 'subcategories': subcategories}

html

{% for category in categories%}
    <a class="dropdown-item" href="{% url 'YourAppName:get_subcategory' pk=category.id %}">{{ category.name }}</a>
{% endfor %}