我是从Django开始的。
我试图将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.
我做错了什么?感谢..
答案 0 :(得分:1)
您不应在浏览器的网址末尾添加test/index.html
,只需添加http://127.0.0.1:8000/,并确保templates/test/index.html
存在。
答案 1 :(得分:0)
Django的url路由使用正则表达式来匹配路由。
url(r'^$', index, name='index'),
在这种情况下,您只有一个有效路由,即空字符串r'^$'
。因此,您只能通过访问http://localhost:8000
来获得回复。所有其他网址都将失败。
Django的url路由完全独立于模板文件在文件系统上的位置。因此,即使存在具有该名称的模板文件,http://localhost/test/index.html
也无效。
您可以使用与任何网址路径匹配的模式制作一个包罗万象的路线。
url(r'', index, name='index'),