Can Django have two views.py files?
Yes, it can have. The views.py file can be split into several files.
In Django everything is a Python module (*.py). You can create a view folder with an __init__.pyinside and you still will be able to import your views, because this also implements a Python module. But an example would be better.
Your original views.py might look like this :
- def view1(arg):
- pass
- def view2(arg):
- pass
With the following folder/file structure it will work the same :
- views/
- __init__.py
- viewsa.py
- viewsb.py
viewsa.py :
- def view1(arg):
- pass
viewsb.py :
- def view2(arg):
- pass
__init__.py :
- from viewsa import view1
- from viewsb import view2
The quick explanation would be: when you write from views import view1 Python will look for view1 in
- views.py, which is what happens in the first (original) case
- views/__init__.py, which is what happens in the second case. Here, __init__.py is able to provide the view1 method because it imports it.
With this kind of solution, you might have no need to change import or urlpatterns arguments in urls.py
If you have many methods in each new view file, you might find it useful to make the imports in views/__init__.py use *, like this:
- from viewsa import *
- from viewsb import *
Articoli simili
- Quali sono le app Django più utili? Quali app rendono il tuo sviluppo Django molto più facile?
- Can you write mobile apps in Python/Django?
- Quali sono i cinque migliori pay-per-views della WWE che avvengono ogni anno e perché?
- Why are the YouTube comment sections always filled with hate and abuse? Can't people just keep quiet if they don’t have anything nice to say?