Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does my controller logic go in Django?

I'm coming from an iOS background to Django. As an app developer, I'm used to clearly defined MVC architecture. My storyboard contains my views. My view controllers contain my logic, and my model exists in an object-relational mapper (ORM) framework or database.

On the web, the separation of responsibility seems less clear cut. Sure, databases and ORMs exists. HTML seems to be my views. Django Models seem to be just that. But where is the controller?

Where does my business logic live?

like image 324
Moshe Avatar asked Mar 11 '26 17:03

Moshe


2 Answers

As the Django FAQ itself points out, Django doesn't quite follow an MVC approach, at least not in a straightforward way. (They argue that Django itself is the controller, but that's not really how I think about MVC.)

The "controllers" in Django are basically what Django calls views. So you have your model classes, which are the M obviously. The templates/HTML are basically the V in MVC. Django views (either functions or classes) are effectively callbacks that run for a particular URL, and they tend to be where a lot of the logic is. So for example, you'll have a Django view called get_foo_bar that runs when someone makes a GET request to /foo/bar, and the Django view effectively becomes the C in MVC.

So long story short, your logic often goes in your Django views.

like image 55
btmcnellis Avatar answered Mar 13 '26 07:03

btmcnellis


Django has controllers that are stored in views.py files, this naming leads to some confusion for newbies with some sort of MVC background, you can read about it here: https://docs.djangoproject.com/en/1.8/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names

like image 44
Eugene Soldatov Avatar answered Mar 13 '26 07:03

Eugene Soldatov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!