简体   繁体   English

如何将视图从一个django views.py导入到另一个

[英]How to import views from one django views.py to another

I am learning Django. 我正在学习Django。 I have 2 functions in my app, one for cats , and another for dogs (as an example). 我的应用程序中有2个功能,一个用于cats ,另一个用于dogs (例如)。 I have the following folder structure: 我具有以下文件夹结构:

/myproject/templates <-- dogs.html, cats.html
/myproject/dogs/ <-- views.py, models.py etc
/myproject/cats/ <-- views.py, models.py etc

Now both cats and dogs have shared views, etc, but currently I am just repeating these in each views.py file. 现在无论是catsdogs有共同的看法,等等,但目前我只是在各个重复这些views.py文件。 Is there a way to "import" views and definitions from one view to another quickly? 有没有一种方法可以将视图和定义从一个视图快速“导入”到另一个视图?

This would save me cut and pasting a lot of the work. 这将节省我剪切和粘贴的大量工作。

What are the dangers of this? 这有什么危险? Eg could conflicts arise? 例如,可能会发生冲突吗? etc. 等等

sure, you can use inheritance and you should use CBV in this case 当然,您可以使用继承,并且在这种情况下应该使用CBV

import Animal

class Dog(Animal):
    ....
    pass

class Cat(Animal):
    ....
    pass

You must change your urls.py as well 您还必须更改urls.py

from django.conf.urls import url
from dogs.views import Dog
from cats.views import Cat

urlpatterns = [
    url(r'^dog/', Dog.as_view()),
    url(r'^dog/', Cat.as_view()),
]

The simplest thing is to have the URLs for cats and dogs point to the same views: 最简单的方法是让猫和狗的URL指向相同的视图:

urlpatterns = patterns(
    'catsanddogs.views',
    url(r'^(?P<kind>dog|cat)/(?P<id>\d+)$', 'details'),
)

And then in catsanddogs.views : 然后在catsanddogs.views

def details(request, kind, id):
    if kind == "dog":
        ... whatever is specific to dogs ...
    elif kind == "cat":
        ... whatever is specific to cats ...
    else:
        raise ValueError("...")

    ... whatever applies to both ...
    return HttpResponse(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM