232
In Django everything is a Python module (*.py). You can create a view folder with an __init__.py
inside 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 urlpattern
s 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 *
I actually donβt know about speed issues (but I doubt there are any).
For Models it might be a bit difficult.
24
Iβve had to do this before (for clarities sake)
The way I did this was to create a views
directory, then, in that, create a file called __init__.py
Now, when youβre calling in your urls.py
, you simply need to add another part
For example, previously, you may have called:-
url(r'^calendar/(?P<year>\d\d\d\d)/$', 'myproject.calendar.views.year')
url(r'^calendar/(?P<year>\d\d\d\d)/(?P<user>[a-z]+)/$', 'myproject.calendar.views.year_by_user')
You can now call something along the lines of
url(r'^calendar/(?P<year>\d\d\d\d)/$', 'myproject.calendar.views.year.index')
url(r'^calendar/(?P<year>\d\d\d\d)/(?P<user>[a-z]+)/$', 'myproject.calendar.views.year.user')
This is, of course, assuming that you had views/year.py
containing the functions index
and user
- [Django]-Jquery template tags conflict with Django template!
- [Django]-Django β Website Home Page
- [Django]-Where can I find the error logs of nginx, using FastCGI and Django?
16
Just for sharing, I had a bit of issues with Vincent Demeesterβs answer. Everything is fine except in init.py file, I have to write in this way:
__init__.py:
from .viewsa import *
from .viewsb import *
This way I still donβt need to change my import
method in urls.py. I am on Python 3.6.1 and Django 1.11.4.
- [Django]-How to access Enum types in Django templates
- [Django]-Pytest.mark.parametrize with django.test.SimpleTestCase
- [Django]-How to view corresponding SQL query of the Django ORM's queryset?
11
Basically, you can put your code, whereever you wish. Just make sure, you change the import statements accordingly, e.g. for the views in the urls.py
.
Not knowing your actual code its hard to suggest something meaningful. Maybe you can use some kind of filename prefix, e.g. views_helper.py
, views_fancy.py
, views_that_are_not_so_often_used.py
or so β¦
Another option would be to create a views
directory with an __init__.py
, where you import all subviews. If you have a need for a large number of files, you can create more nested subviews as your views grow β¦
- [Django]-Django datefield filter by weekday/weekend
- [Django]-Django: sqlite for dev, mysql for prod?
- [Django]-Where can I find the error logs of nginx, using FastCGI and Django?
6
Simple answer: Yes.
Best is to make a directory called views and then in your urls.py do:
import views
...
url(r'^classroom$', views.school.klass, name="classroom"),
- [Django]-How to change empty_label for modelForm choice field?
- [Django]-How to use regex in django query
- [Django]-Django-Bower + Foundation 5 + SASS, How to configure?
2
Vincent Demeesterβs answer is superb! but for me addictedβs answer worked like a charm.
I faced difficulties in migrating database. The error indicates the line where the first model is imported and says could not recognize my app module. Searched a lot but could not find a solution but later on I imported the model like this:
from ..models import ModelName
It worked!!
- [Django]-Django: Use of DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT in settings.py?
- [Django]-Set up a scheduled job?
- [Django]-How do I add a placeholder on a CharField in Django?
1
Since Django just expects a view to be a callable object, you can put then wherever you like in your PYTHONPATH. So you could for instance just make a new package myapp.views and put views into multiple modules there. You will naturally have to update your urls.py and other modules that reference these view callables.
- [Django]-How to pass multiple values for a single URL parameter?
- [Django]-How can I disable logging while running unit tests in Python Django?
- [Django]-How to understand lazy function in Django utils functional module
1
I split almost all views in my apps into a views folder (with an init.py of course). I do not, however, import all of the subviews in the init.py like some of the answers have suggested. It seems to work just fine.
- [Django]-Django switching, for a block of code, switch the language so translations are done in one language
- [Django]-Django migration fails with "__fake__.DoesNotExist: Permission matching query does not exist."
- [Django]-How to define two fields "unique" as couple
1
Iβve been playing with putting this in my init.py:
import os
currPath = os.path.realpath(os.path.dirname(__file__))
dirFiles = []
for root, dirs, files in os.walk(currPath):
for name in files:
if name.endswith('.py') and not name.startswith('_'):
dirFiles.append(name.strip('.py'))
for f in dirFiles:
exec("from %s import %s" % (f,f))
Iβm still new to python, so Iβm still looking at what effect it has on speed/security/ease of use.
- [Django]-Django queryset filter β Q() | VS __in
- [Django]-Paginating the results of a Django forms POST request
- [Django]-Django β How to pass several arguments to the url template tag
1
Suppose if you have a file named: password_generator.py
then inside views.py
add: from password_generator import *
Then you can call that moduleβs function from views.py
.
- [Django]-How can I activate the unaccent extension on an already existing model
- [Django]-Adding css class to field on validation error in django
- [Django]-'pip' is not recognized as an internal or external command