在 Django 中创建类似标签的功能

Creating tag-like feature in Django

我是 Django 的新手,正在尝试找出为我的对象的类别创建 URL 的代码。它现在的工作方式 我为每个类别都有一个 URL 但我正在尝试创建一个快捷方式所以如果我创建更多类别我不必添加另一个 URL 到 URLs.py .

模特:

class Store(models.Model):
    FOOTWEAR = "Footwear"
    CLOTHING = "Clothing"
    OUTERWEAR = "Outerwear"
    ITEM_CATEGORY_CHOICE = (
        (FOOTWEAR, 'Footwear'),
        (CLOTHING, 'Clothing'),
        (OUTERWEAR, 'Outerwear'),
    )
    category = models.CharField(
                   max_length=20,
                   choices=ITEM_CATEGORY_CHOICE,
                   null=True,)

之前每个类别都有一个 url。我能够为特定类别设置 URL:

url(r'^category/(?P<category>[-\w]+)/$',
        'collection.views.specific_category',
        name="specific_category"),

在视图中我遇到了问题。我不确定我在视图中指的是什么:

def specific_category(request, category):
    if category:
        sneakers = Sneaker.objects.filter(category = "__").order_by('-date')

    else:
        sneakers = Sneaker.objects.all().order_by('-date')

现在用代码打开页面是空白的。我觉得答案就在我的脸上,但我看不到。我的模型错了吗?向我指出任何解释的资源也将不胜感激。

您应该做的是创建一个 html 文件来查找通用上下文变量,例如:

category_items.html

Category:
{{ category }}

Items:
{{ for item in items }}
    {{ item.name }}
{{ endfor }}

这样,无论您在视图中过滤什么,您仍然可以使用相同的 html 页面显示结果。此外,将 category = '__' 更改为 category=category,这样它将从 url.

中捕获类别名称

views.py

def specific_category(request, category):
    if category:
        sneakers = Sneaker.objects.filter(category=category).order_by('-date')

    else:
        sneakers = Sneaker.objects.all().order_by('-date')

    return render(request, 'category_items.html', {'category': category, 'items': sneakers})