2015-06-09 70 views
2

出於某種原因,Django是不是在包含數字字符變量月底附加一個斜線:的Python/Django的不追加斜線

test_A - 作品(去test_A /)
TEST_1 - 不(不附加/在最後 - 給我一個404)

我有中間件安裝和APPEND_SLASH =真。

有什麼想法?謝謝!

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. 
+0

什麼是'test_1'和'test_A'?你的意思是「不起作用」?你的輸出是什麼? – sobolevn

+0

他們是環境... syntax

+0

test_A正確地重定向到test_A/... test_1不附加斜槓,所以我得到一個404 – syntax

回答

1

你必須擴展你的正則表達式。問題不在於沒有附加斜槓,問題是沒有一個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'),)

後者甚至會allow /test-1.1_10/

+0

就是這樣!現在完美的工作!非常感謝Wouter! – syntax