gpt4 book ai didi

Python/Django 不附加斜杠

转载 作者:太空宇宙 更新时间:2023-11-04 05:49:55 26 4
gpt4 key购买 nike

由于某些原因,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'),)

模型.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.

最佳答案

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

简单的解决方案,要包含点,您应该更新正则表达式以也允许点: 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/

关于Python/Django 不附加斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30740050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com