Django:支持url()的字符串视图参数已被弃用,将在Django 1.10中删除

Django:支持url()的字符串视图参数已被弃用,将在Django 1.10中删除

问题描述:

新的python / Django用户(实际上是新的):

New python/Django user (and indeed new to SO):

当尝试迁移我的Django项目时,我收到一个错误:

When trying to migrate my Django project, I get an error:

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

显然第二个参数不能再是字符串了。我来创建这个代码,因为它是通过在pluralsight.com的教程,教导如何使用Django与以前的版本(我正在使用1.9)。老师指示我们从我们在应用程序中创建的视图在urls.py中创建urlpatterns。他教我们创建一个urlpattern,如下所示:

Apparently the second argument can't be a string anymore. I came to create this code as it is through a tutorial at pluralsight.com that is teaching how to use Django with a previous version (I'm currently working with 1.9). The teacher instructs us to create urlpatterns in urls.py from the views we create in apps. He teaches us to create a urlpattern such as the following:

from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', 'main.views.home')
]

引用

def home(request):
    return render(request, "main/home.html",
                    {'message': 'You\'ve met with a terrible fate, haven\'t you?'}) #this message calls HTML, not shown, not important for question

在我创建的应用程序主的views.py中。

in the views.py of an app "main" that I created.

如果这个方法被弃用,我该如何传递视图参数而不是字符串?如果我只是删除引号,如文档所示( https://docs.djangoproject.com/ en / 1.9 / topics / http / urls / ),我收到一个错误:

If this method is being deprecated, how do I pass the view argument not as a string? If I just remove the quotes, as shown in the documentation (https://docs.djangoproject.com/en/1.9/topics/http/urls/), I get an error:

NameError: name 'main' is not defined

我尝试使用本文档中提供的代码导入视图或主要使用:

I tried to "import" views or main using the code presented in this documentation:

from . import views

from . import main

这给了我:

ImportError: cannot import name 'views'

ImportError: cannot import name 'main'

我相信我已经追溯到导入错误,目前正在研究。

I believe I've traced this down to an import error, and am currently researching that.

我已经找到了我的问题的答案。这确实是一个进口错误。对于Django 1.10,您现在必须导入应用程序的view.py,然后传递没有引号的url()的第二个参数。这是我的代码现在在urls.py:

I have found the answer to my question. It was indeed an import error. For Django 1.10, you now have to import the app's view.py, and then pass the second argument of url() without quotes. Here is my code now in urls.py:

from django.conf.urls import url
from django.contrib import admin
import main.views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', main.views.home)
]

我没有更改任何内容应用或view.py文件。

I did not change anything in the app or view.py files.

支持@Rik Poggi说明如何在他的答案中导入此问题:
Django - 从单独的应用导入视图

Props to @Rik Poggi for illustrating how to import in his answer to this question: Django - Import views from separate apps