My File Is Quickly Becoming Large. Should I Refactor It?

Eventually, every Django project reaches a state when you ask yourself: should I refactor this file?

Maybe you find yourself jumping around randomly in a huge file. Or it’s just the line count which seems larger than it should be. Are 500 lines too much? How about 2000?

Here are a few questions you can ask yourself to see if you should be worried, and a simple method to make large files more manageable.

Is it really an issue already?

Refactoring should be motivated by an actual problem you’re experiencing. If you can navigate your views without issues, and your work isn’t negatively influenced, maybe you’re not doing anything wrong.

Being worried about line count should make you weary, but large files are not necessarily a bad thing. A huge file can help you spot underlying existing problems, which should be addressed.

Thin views and fat models

A large file, might indicate that you’re doing too much in your views. Is there logic which would be better-off in your models, managers or forms?

Reusable parts

If there are functions which are not views, you could extract them to a single file of helper functions, and import it in your views. Is there maybe even duplicated functionality which could be extracted out of your views?

A views submodule

Split your single file up into multiple ones. Without having to change imports and urls in other places.

It’s pretty straightforward to transition from a single towards a submodule.

First, you need to create a new directory next to your file, called views. Move your file into it, and create an file:


The file should have the following content:

from views import *

At this point, your application will work as expected, but you can begin splitting parts of the big file into smaller parts.

If you have views, which are related to each other, you can add a new file called and move them there. The views folder now looks like this:


Make sure your imports the content of, and you’re good to go!

from views import *
from topic import *

This way, you can split a big file into multiple ones by their topic, and will have an easier time navigating your views in the future, instead of having to scroll through a growing single file.

Splitting files into modules in this fashion is a nice step, before you decide to create dedicated apps in your project.

Want to create better Django apps?

Subscribe for articles about building for the web with Django!

    (About the content, privacy, analytics and revocation).

    We won't send you spam. Unsubscribe at any time.