Whats the correct way to add logic to a view

First, never lose sight of the fact that a Django view is just a Python function that takes a request and returns a response. There’s nothing special or magical about it.

This means you have all the “code organization” facilities available as with any other Python program.

Yes, it’s absolutely ok to break the functionality of the view down into different modules.

Where you physically place that logic is a topic open for (a lot of) discussion. For examples, see the discussions here - Where to put business logic in Django? and here - Structuring large/complex Django projects, and using a services layer in Django projects. (So no, this is far from being a “stupid question” - it wouldn’t generate this amount of conversation if it were.)

Regardless of the organizational structure you adopt, I think it’s most important that you remain consistent within and among projects. Given Python’s flexibility, the issue is that there’s so many different ways of doing this, you want to “minimize surprise” when you (or a teammate) need to go back into the code later to maintain or update it. And that implies having a consistent pattern applied throughout.

1 Like