【问题标题】:How to pass callable in Django 1.9如何在 Django 1.9 中传递可调用对象
【发布时间】:2016-03-13 13:27:50
【问题描述】:

您好,我是 Python 和 Django 的新手,我遵循 django workshop 指南。 我刚刚安装了 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'),

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

【问题讨论】:

  • 该指南似乎是为 Django 1.4 编写的。从那以后发生了很多变化,所以你最好寻找一个不同的教程来学习 Django。
  • 嗯,谢谢(=

标签: python django django-models django-urls django-1.9


【解决方案1】:

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

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),

More documentation and the reasoning can be found here

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

【讨论】:

    猜你喜欢
    • 2012-02-23
    • 2012-08-06
    • 1970-01-01
    • 2013-05-25
    • 2014-08-23
    • 2013-02-20
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多