10

嗨,我是 Python 和 Django 的新手,我遵循django 研讨会指南。我刚刚安装了 Python 3.5 和 Django 1.9 并收到了很多错误消息......刚才我发现了很多文档但现在卡住了。我想添加视图,所以我在 urls.py 中添加了以下代码:

from django.conf.urls import include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = [
    # Uncomment the admin/doc line below to enable admin documentation:
    #url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^rezept/(?P<slug>[-\w]+)/$', 'recipes.views.detail'),
    url(r'^$', 'recipes.views.index'),
]

并且每次都会收到错误消息:

Support for string view arguments to url() is deprecated and will be removed in Django 1.10 (got recipes.views.index). Pass the callable instead.
  url(r'^$', 'recipes.views.index'),

但我找不到如何通过它们。文档仅告诉“通过它们”,但没有示例如何...

4

1 回答 1

20

这是一个弃用警告,这意味着代码现在仍然可以运行。但要解决这个问题,只需改变

url(r'^$', 'recipes.views.index'),

对此:

#First of all explicitly import the view
from recipes import views as recipes_views #this is to avoid conflicts with other view imports

在 URL 模式中,

url(r'^rezept/(?P<slug>[-\w]+)/$', recipes_views.detail),
url(r'^$', recipes_views.index),

更多文档和推理可以在这里找到

在现代,我们更新了教程,改为建议导入您的视图模块并直接引用您的视图函数(或类)。这有许多优点,所有这些都源于我们使用普通 Python 代替“Django String Magic”这一事实:错误输入视图名称时的错误不那么模糊,IDE 可以帮助自动完成视图名称等。

于 2015-12-08T15:02:06.957 回答