Django:使用正则表达式检查请求中的确切网址

时间:2018-12-18 01:54:15

标签: django

我需要检查网址是否准确:

http://127.0.0.1:8000/shop/

并基于此呈现标题。

如果是这样,例如:

http://127.0.0.1:8000/shop/stickers/stickers-por-hoja/medida-y-cantidad

标题不应该呈现。

我读过你可以做这样的事情:

{% if "/shop/$" in request.path %}
    {% include 'header.html' %}
{% endif %}

但这不起作用。另一方面,这可行,但不是我所需要的:

{% if "/shop/" in request.path %}
     {% include 'header.html' %}
{% endif %}

那么,我可以在if条件下使用正则表达式吗?

3 个答案:

答案 0 :(得分:1)

您可以将正则表达式检查移到视图中,并为模板的上下文添加一个字段,如下所示:

class MyView(View):

    def action(self, request, *args, **kwargs):
        shop_in_request = re.findall(r"/shop/$", request.path)
        context = {"include_header": any(shop_in_request)}
        return render(template, context)

然后您可以使用以下视图:

{% if include_header %}
    {% include 'header.html' %}
{% endif %}

答案 1 :(得分:1)

创建一个模板标签即可。

白名单中的网址必须在设置中的某处。例如,您可以添加类似的内容

HEADER_WHITELIST_URLS = (
     'regex1',
     'regex2',
)

2)您的模板标记将检查当前URL,如果其中一个正则表达式匹配,则可以呈现标题。在假设的版本2中,您还可以添加标题以显示特定的正则表达式。

使用此代码段作为模板标签的起点

import datetime
from django import template
from django.conf import settings

register = template.Library()

@register.simple_tag(takes_context=True)
def render_header(context, format_string):
    regexs = settings.HEADER_WHITELIST_URLS

    # maybe you can add some try/exception if the settings is not available.

    for regex in regexs:
        # test the regex with the url in the context.
        # if matches return the code to render the header and break
    return None

在此处查看有关模板标签的更多详细信息:https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/#writing-custom-template-tags

答案 2 :(得分:1)

创建一个具有以下代码的上下文处理器has_shop_in_url.py

import re
def has_shop(request):
    shop_in_request = your_regex_validation

    return {
        'has_shop_in_url':   any([shop_in_request])  }

添加该上下文处理器

TEMPLATES = [
    {
        .....
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'your_module.has_shop_in_url.has_shop' # YOUR PROCESSOR
            ],
        },
    },
]

现在,它可用于整个Web应用程序。在模板中,只需写{{has_shop_in_url}}。您可以看到True/False

相关问题