【发布时间】:2019-08-23 20:44:44
【问题描述】:
我对 Python 3 和 Django 非常陌生,我遇到了以下问题:我使用标准模板,现在当有 1 个视图时如何设置它。但是我没有为多个视图获得正确的代码。我目前在本地运行页面
目前我尝试在 urlpatterns 中更改不同的顺序,当其中只有 1 个 url 时它们确实有效,但我无法获得第二个
views.py
from django.shortcuts import render, render_to_response
# Create your views here.
def index(request):
return render_to_response('index.html')
def store(request):
return render_to_response('store.html')
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from myapp import views as views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^store/$', views.store, name='store'),
url(r'^admin/', admin.site.urls)
]
urlpatterns += staticfiles_urlpatterns()
我想要让我转到索引视图和商店视图的 url 模式
编辑: 完整代码通过以下方式共享:https://github.com/lotwij/DjangoTemplate
【问题讨论】:
-
我不明白问题出在哪里。您的 URL 模式看起来不错 - 您应该能够访问
http://localhost:8000/上的索引视图和http://localhost:8000/store/上的商店视图。一个常见的错误是使用url(r'^', ...)(不带$),然后匹配/和/store/,但这不是问题。 -
请注意
render_to_response已过时 - 请改用render,例如return render(request, 'index.html'). -
当您导航到:localhost:8000/store 时会看到什么?
-
@Alasdair 我编辑了 render_to_response,谢谢 :) @Walucas 我收到以下错误页面:找不到页面 (404) 请求方法:GET 请求 URL:127.0.0.1:8000/store.html 使用 mysite 中定义的 URLconf。 urls,Django 尝试了这些 URL 模式,顺序如下: ^$ [name='index'] ^store/$ [name='store'] ^admin/ ^static\/(?P
.*)$当前路径 store.html 与其中任何一个都不匹配。您看到此错误是因为您的 Django 设置文件中有 DEBUG = True 。将其更改为 False,Django 将显示标准 404 页面。 -
这就是为什么我认为它在 urlspattern 中,就像某种顺序错误.. 但也许我错了..
标签: django python-3.x django-templates url-pattern