python - 尝试组织我的网址

标签 python django django-urls

我的网站针对不同类别有不同的网址,它会根据类别返回过滤后的查询集,例如/sport/ 将返回 Post.objects.filter(category='sport')

网址

urlpatterns = [
    url(r'^news/$', boxes_view, name='news'),
    url(r'^sport/$', boxes_view, name='sport'),
    url(r'^technology/$', boxes_view, name='technology'),
    url(r'^science/$', boxes_view, name='science'),
    url(r'^cars/$', boxes_view, name='cars'),
    url(r'^television/$', boxes_view, name='television'),

    url(r'^(?P<category>\w+)/(?P<id>\d+)/', article, name='article'),

查看

def boxes_view(request):
    category = 'news'
    for a, b in CATEGORY_CHOICES:
        name = resolve(request.path_info).url_name
        if b == name:
            category = a

    posts = Post.objects.all().filter(category=category)

选择.py

CATEGORY_CHOICES = (
    ('1', 'news'),
    ('2', 'sport'),
    ('3', 'technology'),
    ('4', 'science'),
    ('5', 'cars'),
    ('6', 'television')
)

我是否可以只编写 1 个统一的 url 模式来解释所有类别,而不是列出我的 url 中的每个类别?

最佳答案

是的。事实上,看起来你已经成功了。您可以使用正则表达式来识别类别名称并将其传递到 View ,就像处理列表中最后一个 url(“文章”)一样。

尝试这样的事情:

urlpatterns = [
    url(r'^(?P<category>\w+)/$', boxes_view, name='category'), #or whatever name
    url(r'^(?P<category>\w+)/(?P<id>\d+)/', article, name='article'),
]

那么你的 View 将类似于:

def boxes_view(request, category='news'):
    try:
        category_number = CATEGORY_MAP[category]
    except KeyError:
        # return 404?
    posts = Post.objects.filter(category=category_number)
    ... 

然后,您将需要一个类别映射,它就像您的元组一样,但我会使用如下字典:

CATEGORY_MAP = {
    'news': 1,
    ...
}

尽管我需要查看您的更多架构才能确定,但​​从我所看到的情况来看,我建议类别应该是它们自己的模型,然后您可以在 中执行 category__name >发布过滤器并删除从名称到号码的映射。

关于python - 尝试组织我的网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42685767/

相关文章:

django - 应用程序 URL 到项目 URL

python - 在Python中创建一个抽象类

python :error'list' object has no attribute 'sorted'

python - Nginx 无法按预期工作(显示默认页面)(Ubuntu 16.04)

python - django - 如果提交的表单值为 X,则阻止表单提交

python - 在生成 Django 管理 URL 时覆盖查询集过滤器

django - 什么可能导致 flatpages 中的 Page Not Found 错误?

python - PubNub:TypeError:stat:路径应该是字符串、字节、os.PathLike 或整数,而不是 NoneType

python - 在python中覆盖文本文件

django - 如何获取 FileField 中文件的链接?