Django 中 HttpResponse 的疑问

2018-04-02 18:48:35 +08:00
 4thmagi
最近照着 django 官网的文档:编写你的第一个 django 应用( https://docs.djangoproject.com/zh-hans/2.0/intro/tutorial03/)一行行跟着做,但是在第三部分的时候出了问题。往 polls\views.py 中添加更多视图后报错 parameter 'request' value is not used。

代码如下:

from django.http import HttpResponse

def index(request):
return HttpResponse("Hello,world. You're at the polls index.")

def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)

def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)

def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
3881 次点击
所在节点    Django
8 条回复
jackgxc
2018-04-02 18:57:24 +08:00
parameter 'request' value is not used
中文:request 这个参数没有使用

这应该是 IDE 提示的 warning 吧。。。只是提示你没有使用而已
4thmagi
2018-04-02 19:08:50 +08:00
@jackgxc 的确是 IDE 的提示。这个错误出现后,再启动开发服务器,页面会报错 404。
页面报错提示空路径不匹配,我以为是这里没有用到 request 这个参数导致的,具体页面报错如下:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
1.polls/
2.admin/
The empty path didn't match any of these.
wisetc
2018-04-02 21:42:21 +08:00
只是 warning 参数定义但未使用
zc910704
2018-04-02 23:10:42 +08:00
404 的错是因为你 URLconf 你没写对?或者写了没有 include ?
4thmagi
2018-04-02 23:58:11 +08:00
@zc910704 感谢回复!我照着文档执行,在第三部分的向投票应用中添加新视图后,出现了如上所述的访问网站根目录提示 404 的错误。views.py 中添加新视图后也照着文档向 urls.py 中添加了函数调用,但是网站根目录还是出现了 404 错误。后来查了下发现错误原因可能是:文档中并没有手动配置网站“根目录”对应“视图函数”。(出处: https://www.cnblogs.com/edisonfeng/p/3755136.html )这个博客中的 django 版本是 1.几的,我的 django 版本是 2.0.3 的,代码不能直接搬过来用。我还是没搞清楚如何手动配置“根目录”对应“视图函数”,但是我发现:除了根目录,app 的目录还是可以正常访问的。文档后面也没要求访问网站根目录,于是我就先顺着文档往下做了。
gnaggnoyil
2018-04-03 06:48:15 +08:00
url.py 里把 url pattern 到 view 的映射做了没?
toono
2018-04-03 09:11:08 +08:00
@4thmagi 2.x 版本和 1.x 版本的 URLconf 写法不一样。2.x 需要使用 path 函数。

```python
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
```

https://docs.djangoproject.com/zh-hans/2.0/intro/tutorial01/#write-your-first-view
janxin
2018-04-03 10:34:04 +08:00
因为 lz 访问的是主页吧...或者路由没配置好

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/443652

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX