Python / Django不附加斜线

时间:2015-06-09 18:31:52

标签: python regex django

由于某种原因,Django没有在包含数字字符的变量末尾添加斜杠:

test_A - 工作(转到test_A /)
test_1 - 没有(不附加/最后 - 给我404)

我确实安装了中间件,APPEND_SLASH = True。

有什么想法?谢谢!

url.conf:

from django.conf.urls import patterns, url
from dashboard import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^environment/(?P<environment_name_url>\w+)/$', views.environment, name='environment'),)

models.py:

from django.db import models

class Environment(models.Model):
name = models.CharField(max_length=128, unique=True)
def __str__(self):
    return self.name

views.py:

def environment(request, environment_name_url):
    environment_name = environment_name_url.replace('_', ' ')
    context_dict = {'environment_name': environment_name}
    try:
        environment = Environment.objects.get(name=environment_name)
        pages = Page.objects.filter(environment=environment)
        context_dict['pages'] = pages
        context_dict['environment'] = environment
    except Environment.DoesNotExist:
        pass
    return render(request, 'dashboard/environment.html', context_dict)

错误:

Using the URLconf defined in dashboard_project.urls, Django tried these URL patterns, in this order:

    1. ^admin/
    2. ^dashboard/ ^$ [name='index']
    3. ^dashboard/ ^environment/(?P<environment_name_url>\w+)/$ [name='environment']
    4. media/(?P<path>.*)

The current URL, dashboard/environment/test_1, didn't match any of these.

1 个答案:

答案 0 :(得分:1)

您必须扩展正则表达式。问题不在于没有附加斜杠,问题是没有网址匹配(有或没有斜杠)。

简单的解决方案,要包含点,您应该更新正则表达式以允许点: url(r'^environment/(?P<environment_name_url>[\w\.]-)/$', views.environment, name='environment'),)

您可以进一步改进它以允许破折号: url(r'^environment/(?P<environment_name_url>[\w\.-]+)/$', views.environment, name='environment'),)

后者甚至允许/test-1.1_10 /