QNA > C > Can Django Have Two Views.py Files?

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 :

  1. def view1(arg): 
  2. pass 
  3.  
  4. def view2(arg): 
  5. pass 

With the following folder/file structure it will work the same :

  1. views/ 
  2. __init__.py 
  3. viewsa.py 
  4. viewsb.py 

viewsa.py :

  1. def view1(arg): 
  2. pass 

viewsb.py :

  1. def view2(arg): 
  2. pass 

__init__.py :

  1. from viewsa import view1 
  2. from viewsb import view2 

The quick explanation would be: when you write from views import view1 Python will look for view1 in

  1. views.py, which is what happens in the first (original) case
  2. 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:

  1. from viewsa import * 
  2. from viewsb import * 

Di Sweyn Mcdorman

Come creare dinamicamente le variabili in Python :: Come inserire un dict dinamico con una chiave e un valore inseriti da input in Python 3.6
Link utili