gpt4 book ai didi

python - Django 无法分割 View

转载 作者:行者123 更新时间:2023-12-01 04:39:25 27 4
gpt4 key购买 nike

我最近开始采用 Python 和 Django 框架。它有很多很棒的事情,也有很多我真的很讨厌的事情。其中之一是每个 Django 应用程序都有一个 views.py 文件,我发现这非常不切实际。所以我决定将我的 View 分成多个文件。事实证明,这比我最初想象的要困难得多。

我遵循了很多问题和教程,但没有一个起作用。我应该补充一点,我在 ArchLinux 和 Django 1.8 上使用 Python 3.4。

我原来的设置(我简化了,其实还有更多的查看功能):

View .py

def entries(request):
...

def delete_entry(request, id):
...

def categories(request):
...

def delete_category(request, id):
...

url.py

from django.conf.urls import patterns, url
from transactions import views

urlpatterns = patterns('',
url(r'^entries$', views.entries, name='entries'),
url(r'^delete_entry(?:/(?P<id>[0-9]+)/)?$', views.delete_entry, name='delete_entry'),

url(r'^categories$', views.categories, name='categories'),
url(r'^delete_category(?:/(?P<id>[0-9]+)/)?$', views.delete_category, name='delete_category'),
)

我想要的状态是:

查看包含entries.py和categories.py的文件夹:

编辑:views文件夹中有一个init.py文件。

条目.py

def entries(request):
...

def delete_entry(request, id):
...

类别.py

same logic as above

我在此设置中使用的 urls.py:

from transactions.views import entries, categories
from django.conf.urls import patterns, url

urlpatterns = patterns('',
url(r'^entries$', entries.entries, name='entries'),
url(r'^delete_entry(?:/(?P<id>[0-9]+)/)?$', entries.delete_entry, name='delete_entry'),

url(r'^categories$', categories.categories, name='categories'),
url(r'^delete_category(?:/(?P<id>[0-9]+)/)?$', categories.delete_category, name='delete_category'),
)

当我尝试manage.py runserver时,会引发ViewDoesNotExists错误,并显示无法导入'transactions.views.entries'。 View 不可调用。 消息。当我尝试在 urls.py 中转储 entries.entries 时,它实际上是一个函数,与原始设置相同。

到目前为止,我已经尝试了来自 this 的大量建议。诸如导入变体、在 View 文件夹中破解 __init.py__ 、使用不带 __init__.py 的 View 文件夹等问题,但结果几乎相同或存在导入错误。

最佳答案

没有什么比“每个 Django 应用程序一个views.py 文件”更好的了。 startapp 命令只是为您创建一个views.py 文件,只是为了将代码放在某处。 View 函数可以存在于任何地方,只要它位于 Python 路径上即可。这意味着它必须是可导入的,因此注释表明您可能在 views 文件夹中缺少 __init__.py

Writing views

A view function, or view for short, is simply a Python function thattakes a Web request and returns a Web response. This response can bethe HTML contents of a Web page, or a redirect, or a 404 error, or anXML document, or an image . . . or anything, really. The view itselfcontains whatever arbitrary logic is necessary to return thatresponse. This code can live anywhere you want, as long as it’s onyour Python path. There’s no other requirement–no “magic,” so tospeak. For the sake of putting the code somewhere, the convention isto put views in a file called views.py, placed in your project orapplication directory.

关于python - Django 无法分割 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31075064/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com