tags:

views:

830

answers:

4

If the app/views.py file gets very large, should I separate it? If so, what is the best way to do this?

+2  A: 

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
Josh Smeaton
+10  A: 

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.

Van Gale
+1  A: 

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 :)

winsmith
+2  A: 

There is no generic best way. But there is a right way for your situation.

  • put the views in their own files and import them in your view. This is good just to see how it works
  • make a separate app inside the project to maintain a set of views
  • create your own generic views which share the views common to most of your apps

Just as an starting example: I recommend you to start from the model and work yourself up:

  • how many models do you have?
  • Do they actually all relate or can they be grouped?
  • if the can be grouped split the app into two apps
  • so you'll also split the views
  • determine which view functions are similar and make them generic.
Andre Bossard