Django: Since it is not strictly MVC, but MTV, what is "view"? [duplicate] - django

This question already has answers here:
MVC pattern in django
(7 answers)
Closed 9 years ago.
I'm new to Django and I read two somewhat contradictory things about it. One source says that it is based on MVC (Model-view-controller) style, other argues that it is MTV (Model-template-view). I understand it as MTV. Am I correct in my view? No pun intended.
If it is, I'm still confused by the two notions of "view", since they are different in two contexts.
Django documentaion says:
A view is a “type” of Web page in your Django application that generally serves a specific function and has a specific template.
To me this sounds like the view is a function-with-template.
Does anyone have a clear understanding of the situation? And a good, the simpler the better, explanation. Maybe some analogies?

I think you are getting confused by patterns and styles and analogies and acronyms.
Django has a file named urls.py, that maps incoming requests to views. A view is a function (or class implementing some methods) of which the return value (a HTTPResponse, usually) is sent back to the browser. Often, but not necessarily always, views use templates to make that return value.
Django also has an ORM layer (a mapping between Python classes and database tables), and such classes representing database tables are called "models". Views often need information from the database, and they call functions on the models to get it.
Another core part of Django is the form handling. Views often need to get parameters from the request (like from submitted forms) and they use forms for that.
And that's Django. If that is obviously some acronym pattern to you, feel free to consider it that...

Views are the places where we use to write the Business Logic. Business Logic can be written anywhere in the project but it is suggested to write it in the views.
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really. The view itself contains whatever arbitrary logic is necessary to return that response. This code can live anywhere you want, as long as it’s on your Python path. There’s no other requirement–no “magic,” so to speak. For the sake of putting the code somewhere, the convention is to put views in a file called views.py, placed in your project or application directory.
Go through the docs for a much clear idea.
https://docs.djangoproject.com/en/1.6/topics/http/views/#writing-views

Related

What does django controllers are in views.py

I have followed several django tutorials. I do not know why controllers are stored in a file called views.py. I am confuse with this filename. I am looking for a MVC development. Are there other files in django for "real" controllers ?
The name views.py was a mistake
From an architecture point of view, it was a mistake to call views.py the module where functions receive an HTTP request and produce an HTTP response.
Such module is clearly a controller in the MVC sense. (For comparison, the equivalent functionality in the Spring framework is in a class with annotation #RestController or #Controller.)
Such module is also a REST adapter if you use the Ports & Adapter architecture style (aka Hexagonal architecture).
Such module deals with in-out data (request-response), but it is not a representation of the view displayed to the user. If not, what about an http DELETE endpoint (#api_view(['DELETE']))? What about an http POST endpoint that triggers background processing and has no bearing on what the Web UI shows? The functions in views.py are "handlers" of user actions (i.e., controller in MVC), not the representation of UI data.
I understand that views.py is a convention and you can use other names, but once the tutorial examples and other documentation use that name, it sticks.
Another mistake is when tutorials like this use the name views.py as the single place for all http endpoints. The name views.py is too generic and its very idea is an invitation to violate the Single Responsibility Principle (SRP).
Even simple tutorial examples, should use better names. For example:
if you're handling endpoints that deal with customer functionality, call it views_customer.py or customer_views.py (or better yet, customer_controller.py if you're bold to break with the convention and call it for what it is).
Yes ! Actually it's a design decision and It's described by the guys behind Django Here.
Basically their argument is that, in their opinion,
In our interpretation of MVC, the “view” describes the data that gets presented to the user. It’s not necessarily how the data looks, but which data is presented. The view describes which data you see, not how you see it. It’s a subtle distinction.
a “view” is the Python callback function for a particular URL, because that callback function describes which data is presented.
I entice you to read the entry to get a hold of the overal idea behind the views naming.
About the controllers, Yes again. Mostly though, you can define several layers of the so called Middlewares in django to handle lots of your static logic before/after requests are handled by views, but still, it's the view that plays the main role of a controller in Django.
Look at this logically. What do you normally call a text file with placeholders which is filled with other bits of text by supplying variables? You call that a "template", you don't call that a "view". Only in MVC would you think of calling such a thing a "view".

Django project applications division

I'm currently writing django project and got confused when it came to separation into apps. Project consists of posts and categories which are kept in one app, also there is a 'main' app which handles user profile view, login, logout and registration. Now I'm trying to implement user-to-user messages and I'm wondering if it should be kept as separate app.
If Message model is kept in application 'messages' how do I realize show_messages view?
1) It seems that it should be stored in 'main' app since it's linked by my_profile view. It would just get all Message instances form 'messages' app and render template extending profile.html or including from 'messages' app a partial template responsible only for messages listing. But why would I then need separate application just to hold one model there with some helper functions?
2) Secondly I wonder about placing show_messages view in 'messages' app but then I would need to use template which extends template from other application which again seems to be violation of self-containment rule. Also all "accounts/" urls are currently kept in main.urls so I feel wrong about adding "accounts/profile/messages" rule to messages.url.
3) Finally I think about moving Message model with all helpers and templates to 'main' app since messages are designed to work with User models and views therefore forcing additional separation seems useless.
Thanks for reading my thoughts, I'll appreciate all clues and explanations.
When I first started working with Django, I found the answers on this SO question to be particularly helpful, regarding app/project layout: Projects vs Apps
Many of the answers are useful, but this one is particularly pithy:
Try to answer question: "What does my application do?". If you cannot answer in single sentence, then maybe you can split it to several apps with cleaner logic?
I've read this thought somewhere soon after I've stared to work with django and I find that I ask this question my self quite often and it helps me.
Your apps don't have to be reusable, they can depend on each other, but they should do one thing.
Interdependence of apps isn't always problematic. For example, in a lot of my projects I have a separate app that is used solely for creating dynamic menus. In order to work properly, I need to import the specific models of that site into that app -- so I couldn't just drop it into another site, unaltered, and expected it to work. Nonetheless, the other 90% of the code in that app is completely reusable, and it's easier for me to move the relevant code to a new project if its already spun out into a separate app -- even though that app only holds a templatetag and a template.
Ultimately, a django site would technically run just fine with ALL models/views/etc in one big, unwieldy app. But by breaking your project down into "this app performs this specific function" you're probably going make managing your code a lot easier for yourself.
Regarding the 'url' point in 2, there's no reason not to subspace URLs. You are already doing this in a django project already -- mostly likely your main urls.py has an include() to another app, such as your main.urls. There's no reason your main.urls can't also have an include() to your messages app.

MVC pattern in django

This issue has been tormenting me for a while already. I've read about this topic but nothing seems to clear my thoughts. I understand that they call the views templates, and the models models as well, what I don't really get is where the controllers are. What django calls views seem to me more like actions/methods/functions of a controller than a controller itself, but anywhere I read, I find that supposed view-controller equivalency.
I've worked with MVC frameworks before (ASP.NET MVC3, Ruby on Rails, PHP Laravel Framework), and they all define the controllers as the same thing: a bunch of functions related to a specific topic of the site, namely user accounts or something like that. The best equivalency that I find between this description and django features are the apps, but of course I'm wrong due to the huge amount of people and documentation going the other way.
Could anybody help me with this? Does my mindset make any sense? Am I missing something essential here and then I can't get these concepts right?
It's a mistake to think of design patterns like MVC as unbreakable rules. They really aren't: there are all sorts of ways of implementing them, which comply with the description to a greater or lesser extent.
This is especially the case in Python, where one of the guiding principles is "practicality beats purity" - in other words, do what works.
In any case, Django makes no claim to be an MVC framework. On the contrary, the documentation describes it as MTV: model, template, view. After all, outside the world of design patterns everyone calls "an HTML file with syntax for variables and flow control" a template, not a view.
(That FAQ entry also offers a possible answer to your question: the controller is the framework itself. But it goes on to emphasise that it's a mistake to try to shoehorn into these definitions.)
The views.py defines the view functions for your app and your app groups related functions together.
However what I believe you're missing here is the urls.py.
The urls file is the first part of the controller.
The URL patterns inside urls.py dictates what you're allowed to pass in to the view function or view class (depending on what approach you took, either with function based views or class based views) and then routes it to the proper view function.
So there's tight a coupling between the views.py and the urls.py, that makes up for the entire Controller part of MVC.
Comparing it to Rails, would be that the urls.py is a routes.rb and the actual controller class is the views.py function/cbv.
The mismatch of terminology is unfortunate but more or less doing the same thing.
You can read the Django FAQ. It explains the how MVC is implemented in django. Regarding controller Django has an answer as:
.
Where does the “controller” fit in, then? In Django’s case, it’s probably the framework itself: the machinery that sends a request to the appropriate view, according to the Django URL configuration.
Could anybody help me with this? Does my mindset make any sense? Am I missing something essential here and then I can't get these concepts right?
The only well-defined parts of MVC where nearly everyone had some sort of consensus is the M; the V and C means completely different things in different web frameworks, to the point where MVC framework really only means as not having all your code in one spaghetti (ala typical classical PHP code). You just had to accept that MVC isn't a really well defined term.
Django is not strictly speaking MVC.
I found this discussion very enlightening:
Django is not MVC
Realy guys:
DJANGO is MVC!
But word View use for Controller.
And Django is Full MVC, but
Model - Model
View - Template
Comtroller - View

how to make interaction between different django apps in a single site?

I have just learnt about Django apps. I want to know that within one site, if I make different apps. like, users, profiles, polls, blogs,comments, jobs , applications then how can I manage them to make them intereactive? And is it how the concept of app should be? I want to have things loosely coupled that's why asking? Rails work on the way of REST, so do Django support that also with the use of apps? May be my questions seems a bit ambiguous because I am new to django and some of my concepts are still messed up.
Please tell what ever you know.
The general idea is that apps should be as loosely coupled as possible. The goal is to have completely self-contained functionality. Now, of course, that's not always possible and many times it even makes sense to bring in functionality from another app. To do that, you simply import whatever you need. For example, if your "blogs" app needed to work with your Comment model in your "comments" app you'd simply add the following to the top of the python file you're working in:
from comments.models import Comment
You can then use Comment as if it were defined right in the same file.
As far as REST goes, Django's views are much more fluid. You can name your view whatever you like; you need only hook it up to the right urlpattern in urls.py. Django views can return any content type, you just prepare the response and tell it what mimetype to serve it as (the default is HTML).

Alternate URL router for Django

How would you go about using django models and templates, but not the URL routing system? I'd like to swap out the urls.py system for something like PHP where the URL tells you exactly where the code is that's running. Or maybe something more automagic like rails uses -- where the URL always includes the same components like app name, model name and view name.
I just disagree with the line from the django philosophy statement that "Tying URLs to Python function names is a Bad And Ugly Thing." Pretty URLs just aren't all that important to me, and IMVHO not worth the complexity of climbing through a maze of indirection in multiple urls.py files and dozens of regexes to find out what code runs behind a particular URL. It's a personal choice, right? Django is generally pretty modular allowing you to swap out the major components for other ones. So, how would I swap out the part which takes the request URL and decides which view to run?
Are there any alternate URL routers for django out there?
All you need is one line in your urls.py that matches everything, and then just write your handler/dispatcher as a view. That handler does whatever you want based on the parts of the URL....
I've never heard of anyone successfully swapping out Django's URL routing system. There's certainly no hook for it - core.handlers.base.BaseHandler.get_response calls urlresolvers.RegexURLResolver directly. Conceivably, you could add a middleware at the bottom of the stack that dispatches to your own URL resolution system and returns the response, thus bypassing the Django system, but it's a bit kludgy.
If you're after something more like Rails, you might want to try one of the other frameworks - Pyramid, for example, uses a system of Routes very similar to Rails'. Pyramid is much more pluggable than Django, so you should be able to plug in the Jinja2 templating system, which is based on Django's. However, there's no way to use Django's ORM seperately, so you'd need to use SQLAlchemy (which can be used in a way that's not massively different).