If the app/views.py file gets very large, should I separate it? If so, what is the best way to do this?
Splitting the Views view_a . Remove the views.py file and create a directory named views. Add a __init__.py file inside it and create the separated view files. This is an important step: import all the modules inside each view file.
The view describes which data you see, not how you see it. It's a subtle distinction. So, in our case, a “view” is the Python callback function for a particular URL, because that callback function describes which data is presented.
from django. shortcuts import render from django. http import HttpResponse def index(request): return HttpResponse("Hello World!") (Of course you can give any url to your my_new_app in your project's urls.py file.)
Some developers make their views a python package instead of a module. This simply means making a directory called views
in your application then placing each view in its own module (file) in that package.
Then you create an __init__.py
file (which is what makes it a package). This file can be empty or it can be import all the view modules into its own namespace.
If it is empty you would have to import each view you need directly otherwise you can import it just as though it were a views.py module.
There is no generic best way. But there is a right way for your situation.
Just as an starting example: I recommend you to start from the model and work yourself up:
I'd separate out views with similar purpose or functionality into one file, and include that in views.py. I only do this for readability and maintenance. For instance, CRUD views for a particular object or group of objects.
By importing these views directly into the main views.py file, it allows people not familiar with your convention to find what's where.
views/object_view.py
In an ideal world, you shouldn't have to do this. Instead, try to refactor your code into different django apps for each sub-purpose that your project needs. That way, you can partition your project even better than you could have if you only split the views.py file.
For tips on how to split up your project into different apps, I recommend reading James Bennett's Practical Django Projects, which is what I'm re-reading right now :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With