2016-12-02 66 views
0

我開始在Django。Django - 沒有在模板中顯示我的var

我想通過我的模板我的var將顯示在我的瀏覽器中,但無法正常工作。

這裏是我的views.py

from django.shortcuts import render 
from django.http import HttpResponse 
from preguntasyrespuestas.models import Pregunta 
from django.shortcuts import render_to_response 

# Create your views here. 
def index(request): 
    string = 'hi world' 
    return render_to_response('test/index.html', 
           {'string': string}) 

這裏是我的網址:

from django.conf.urls import * 
from django.contrib import admin 
from django.contrib.auth.views import login 
from preguntasyrespuestas.views import index 

urlpatterns = [ 
    url(r'^$', index, name='index'), 
] 

我的html:

<!DOCTYPE html> 
<html> 
<head> 
    <title> Preguntas </title> 
</head> 
<body> 
    <p>{{ string }}</p> 
</body> 
</html> 

Basicaly我想展示一下我的模板是在string。但沒有工作..

我的錯誤:

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

    ^$ [name='index'] 

The current URL, test/index.html, didn't match any of these. 

我在做什麼錯?謝謝..

回答

1

你不應該在瀏覽器的url結尾加上test/index.html,就像http://127.0.0.1:8000/一樣,並確保templates/test/index.html存在。

0

Django的url路由使用正則表達式來匹配路由。

url(r'^$', index, name='index'), 

在這種情況下,您只有一個有效路由,它是空字符串r'^$'。因此,您只能通過訪問例如http://localhost:8000來獲得回覆。所有其他網址都會失敗。

Django的url路徑完全獨立於您的模板文件在文件系統上的位置。因此,即使存在具有該名稱的模板文件,http://localhost/test/index.html也無效。

您可以通過使用此模式來匹配任何url路徑,從而製作全路徑路線。

url(r'', index, name='index'),