Confused by Django's claim to MVC, what is it exactly? - python

So what exactly is Django implementing?
Seems like there are
Models
Views
Templates
Models = Database mappings
Views = Grab relevant data from the
models and formats it via templates
Templates = Display HTML depending on data given by Views
EDIT: S. Lott cleared a lot up with this in an edit to a previous post, but I would still like to hear other feedback. Thanks!
Is this correct? It really seems like Django is nowhere near the same as MVC and just confuses people by calling it that.

Django's developers have a slightly non-traditional view on the MVC paradigm. They actually address this question in their FAQs, which you can read here. In their own words:
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.
So, in our case, a “view” is the Python callback function for a particular URL, because that callback function describes which data is presented.
Furthermore, it’s sensible to separate content from presentation – which is where templates come in. In Django, a “view” describes which data is presented, but a view normally delegates to a template, which describes how the data is presented.
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.

Related

Is Django a MVC or MVT framework?

I was wondering that whether Django is a MVC or MVT framework? I searched this question on net but didn't find any suitable or satisfactory answer.
I found a partial answer to this question directly in Django's FAQs
https://docs.djangoproject.com/en/3.1/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
Quoting directly here for convenience:
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?
Well, the standard names are debatable. 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. So, in our case, a “view”
is the Python callback function for a particular URL, because that
callback function describes which data is presented. Furthermore, it’s
sensible to separate content from presentation – which is where
templates come in. In Django, a “view” describes which data is
presented, but a view normally delegates to a template, which
describes how the data is presented. 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. If you’re hungry for acronyms, you might
say that Django is a “MTV” framework – that is, “model”, “template”,
and “view.” That breakdown makes much more sense. At the end of the
day, it comes down to getting stuff done. And, regardless of how
things are named, Django gets stuff done in a way that’s most logical
to us.
Django is an MVT based framework. And in that “M” stand for Model “V” stands for View & “T” stands for Template
Model: The Model is the logical data structure behind the entire application and is represented by a database(generally relational databases such as MySql, Postgres).
View: View is the main functionality part of Django architecture, where we write the business logic which is going to be responsible for request and response according to the client inputs.
Template: By the name itself it's showing its behavior. The template is the part that is used for the representation of HTML pages on the web browser.
If you want more specific detail about django mvt architecture, you can refer to this article which I found good and they have explained very well with a diagram representation Django MVT Architecture
Django follows MVC pattern very closely but it uses slightly different terminology. Django is essentially an MTV (Model-Template-View) framework. Django uses the term Templates for Views and Views for Controller. In other words, in Django views are called templates, and controllers are called views. Hence our HTML code will be in templates and Python code will be in views and models.
A complete explanation of this can be found here - https://overiq.com/django-1-10/mvc-pattern-and-django/
Djnago follows MVT framework.M=model V=views. T=templates
https://www.geeksforgeeks.org/django-project-mvt-structure/

What are the differences between Generics, Views, Viewsets and Mixins in Django?

I am new to Django and Django-Rest. I am confused about when I should use these? what are their advantages and disadvantages? I have only seen this- http://www.cdrf.co
The only thing I know is there are a lot of ways to do 1 thing. But this is totally unclear to me.
In Django, these four terms we use frequently for different purposes in the projects. I have tried to collect and share the actual meaning with the links to details description of each term. Please check if you find these helpful.
Generic views:
“Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.”
— Django Documentation
Read more details
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.
Read more details
Viewsets:
Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet. In other frameworks, you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides actions such as .list() and .create().
The method handlers for a ViewSet are only bound to the corresponding actions at the point of finalizing the view, using the .as_view() method.
Read more details
Mixins:
The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as .get() and .post(), directly. This allows for more flexible composition of behavior.
The mixin classes can be imported from rest_framework.mixins.
Read more details

business logic in Django

I'd like to know where to put code that doesn't belong to a view, I mean, the logic.
I've been reading a few similar posts, but couldn't arrive to a conclusion.
What I could understand is:
A View is like a controller, and lot of logic should not put in the controller.
Models should not have a lot of logic either.
So where is all the logic based stuff supposed to be?
I'm coming from Groovy/Grails and for example if we need to access the DB or if we have a complex logic, we use services, and then those services are injected into the controllers.
Is it a good practice to have .py files containing things other than Views and Models in Django?
PS: I've read that some people use a services.py, but then other people say this is a bad practice, so I'm a little confused...
I don't know why you say
we can't put a lot of logic in the controller, and we cannot have the models with a lot of logic either
You can certainly put logic in either of those places. It depends to a great extent what that logic is: if it's specifically related to a single model class, it should go in the model. If however it's more related to a specific page, it can go in a view.
Alternatively, if it's more general logic that's used in multiple views, you could put it in a separate utility module. Or, you could use class-based views with a superclass that defines the logic, and subclasses which inherit from it.
Having a java background I can relate with this question.
I have been working on python for quite some time. Even though I do my best to treat Java as Java and Python as Python, some times I mix them both so that I can get a good deal out of both.
In short
Put all model related stuff in models app, it could be from simply models definition to custom save , pre save hooks .....
Put any request/ response related stuff in views, and some logic like verifying Jon schema, validation request body ... handling exceptions and so on ....
Put your business logic in separate folder/ app or module per views directory/ app. Meaning have separate middle module between your models and views.
There isn't strict rule to organise your code as long as you are consistent.
Project : Ci
Models: ci/model/device.py
Views: ci/views/list_device.py
Business logic:
(1) ci/business_logic/discover_device.py
Or
(2) ci/views/discover_device.py
Short answer: Django is more of a MTV or MVT (Model / Template / View), as described in the official FAQ : https://docs.djangoproject.com/en/dev/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
The business logic has its place in your views, but nothing prevents you from putting it inside a "utils.py", "services.py" or anything to your liking.
If the functionality fits well as a method of some model instance, put it there. After all, models are just classes.
Otherwise, just write a Python module (some .py file) and put the code there, just like in any other Python library.
Don't put it in the views. Views should be the only part of your code that is aware of HTTP, and they should stay as small as possible.

Django - Managing page content in Django Admin

I'm new to working with Django and am developing for a client who wants to be able to change page content in the Django Admin. They need to be able to change the html of the index page without editing the files on the server.
I know about flatfiles but I'm not sure that's completely what I'm after as I can't display stuff such as Django forms for example.
EDIT: Kind of like how a CMS works but without the users/group stuff and be able to use Django View modules such as forms.
Any advice?
Thanks
Honestly, the scope of what you're looking for is too huge to cover in this format. There's a number of ways this could be done, but they're all going to require some work and customization based on the client's needs.
Flatpages could work if you allow HTML content and make sure the content is rendered as "safe" in the template. This really only covers the "content" area of the site, though. It wouldn't be wise to use flatpages for an entire site template, including header, sidebar, footer, etc.
You could create editable areas. So, you actually create models for things like headers, sidebars, footers, and modules within those areas, and then just pull them into the template as needed. Then, the client is only editing pieces of the template instead of responsible for the whole HTML document.
Forms are going to be a challenge, because they require backend-processing that requires a connected view. The client won't be able to just arbitrarily drop in some form code and have a form. But, you could use a third-party service form forms and just embed them in the available content regions. Or, there's a couple of django apps that try to implement a type of "form builder" in the admin. That might somehow let the client add a form via something like the shortcodes used in Wordpress, but you'd likely have to lay down some infrastructure to make that work.
At a certain point, stuff like this reaches a point of diminishing returns, though. The only way to allow total customization of the template is to drop down into the actual physical file and make changes there. You can make certain things easier for the client, but ultimately, they either need to scale back their customization needs or deal with the fact that they'll have to work with the filesystem.
I don't believe that is possible at this time. Of course you can edit your models but templates, I think not.
I would find out how much they need to change? If they plan a complete redesign every week then you're still looking for an answer. If they just need a dynamic front page then you can split it up into variables and let them edit sections of html. Much safer and less prone to breaking the html.

Simple RESTFUL client/server example in Python?

Is there an online resource that shows how to write a simple (but robust) RESTFUL server/client (preferably with authentication), written in Python?
The objective is to be able to write my own lightweight RESTFUL services without being encumbered by an entire web framework. Having said that, if there is a way to do this (i.e. write RESFUL services) in a lightweight manner using Django, I'd be equally interested.
Actually, coming to thing of it, I may even PREFER a Django based solution (provided its lightweight enough - i.e. does not bring the whole framework into play), since I will be able to take advantage of only the components I need, in order to implement better security/access to the services.
Well, first of all you can use django-piston, as #Tudorizer already mentioned.
But then again, as I see it (and I might be wrong!), REST is more of a set of design guidelines, rather than a concrete API. What it essentially says is that the interaction with your service should not be based on 'things you can do' (typical RPC-style methods), but rather 'things, you can act on in predictable ways, organized in a certain way' (the 'resource' entity and http verbs).
That being said, you don't need anything extra to write REST-style services using django.
Consider the following:
# urlconf
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url(r'^tickets$', 'myapp.views.tickets', name='tickets'),
url(r'^ticket/(?P<id>\d+)$', 'myapp.views.tickets', name='ticket'),
url(r'^ticket$', 'myapp.views.tickets', name='ticket'),
)
# views
def tickets(request):
tickets = Ticket.objects.all()
return render_to_response('tickets.html', {'tickets':tickets})
def ticket(request, id=None):
if id is not None:
ticket = get_object_or_404(Ticket, id=id)
if request.method == 'POST':
# create or update ticket here
else:
# just render the ticket (GET)
...
... and so on.
What matters is how your service is exposed to its user, not the library/toolkit/framework it uses.
This one looks promising. http://parand.com/say/index.php/2009/04/30/django-piston-rest-framework-for-django/ I've used it before and it's pretty nifty. Having said that, it doesn't seem maintained recently.

Categories