【问题标题】:django listing by category , with indexview and detailview classesdjango 按类别列出,带有 indexview 和 detailview 类
【发布时间】:2020-05-15 20:50:14
【问题描述】:

我正在对列表和详细信息使用通用视图,在索引页面上我得到了我的列表但没有得到我的类别列表,但我得到了另一个模板上的类别列表。 我想在索引页面上列出类别,然后单击该类别,图像转到按该特定类别过滤的列表。 我希望你能理解我的问题 .下面是品牌索引和类别模型的视图

class BrandsIndexView(generic.ListView):
    template_name = "brands/index.html"
    context_object_name = "latest_brands_list"

    def get_queryset(self):
        return Brands.objects.filter(created_on__lte=timezone.now()).order_by('-created_on')[:10]

model for category 

class Category(models.Model):

    category_name = models.CharField(null=False,max_length=200)
    category_slug = models.SlugField(
        max_length=200, db_index=True, unique=True)
    category_image = models.FileField(upload_to="brand_cat_images",null=True,blank=True,validators=[file_ext])

class Brands(models.Model):
    brand_name = models.CharField(max_length=200 , null=False,help_text="Enter Brand Name")
    brand_slug = models.SlugField(max_length=200 , unique=True)
    brand_logo = models.ImageField(null=False, blank=False, upload_to="brand_logo")
    brand_description = models.TextField(max_length=250 ,null=True,blank=True)
    brand_category = models.ForeignKey(Category,on_delete=models.CASCADE ,default="None",related_name="category")

【问题讨论】:

  • 提供您正在编写的代码,例如模型和视图,以供我们理解。
  • 再次检查问题我添加了代码
  • 你的品牌型号在哪里?
  • 添加到代码中

标签: django django-views django-templates


【解决方案1】:

您需要创建一个按类别 slug 过滤的品牌列表视图,然后定义一个接受类别 slug 作为参数的 url。 您可以使用如下 get_queryset 方法:

def get_queryset(self):
    cat_slug = self.kwargs['slug']
    cat = Category.objects.get(category_slug=cat_slug)
    qs = cat.brands_set.order_by('brand_name')
    return qs

示例网址:

    path('categories/<slug>', views.BrandsListView.as_view(), name='brand_category'),

模板示例:

      <a href="{% url 'brand_category' 'some_category' %}">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-17
    • 2011-07-01
    • 1970-01-01
    • 2012-07-03
    • 2010-11-21
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多