3 minute read

Model View Controller (MVC)

  • The MODEL represents the information (the data) of the application and the business rules used to manipulate the data
    • The persistent data that we keep in the data store
  • The VIEW corresponds to elements of the user interface such as text, checkbox items, and so forth
    • The HTML, CSS, etc. which makes up the look and feel of the application
  • The CONTROLLER manages details involving the communication to the model of user actions
    • The code that does the thinking and decision making

Tasks inside the server

  • Process any user input data - possibly storing it in a database or making some other change to the database such as a delete
  • Decide which screen to send back to the user
  • Retrieve any needed data
  • Produce the HTML response and send it back to the browser

Views and Templates

Views are the core of an application

  • Django looks at the incoming request URL and uses urls.py to select a view
  • The view from views.py
    • Handle any incoming data in the request and copy it to the database through the model
    • Retrieve data to put on the page from the database though the model
    • Produce the HTML that will become the response and return it to the browser

Reading the URL

  • When Django receives an HTTP request it parses it, uses some of the URL for routing purposes and passes parts of the URL to your code
  • URL dispatcher

Three Patterns for views (in urls.py)

  • Requests are routed to a pre-defined class from Django itself
  • Requeste are routed to a function in views.py that takes the http request as a parameter and returns a response
  • Requests are routed to a class in views.py that has get() and post() methods that take the http request as a parameter and return a response
#urls.py

from django.urls import path
from . import views
from django.views.generic import TemplateView

app_name='views'
urlpatterns=[
	#pre-defined class from Django
	path('', TemplateView.as_view(template_name='views/main.html')),
	#function from views.py
	path('funky', views.funky),
	path('danger', views.danger),
	path('game', views.game),
	path('rest/<int:guess>', views.rest),
	path('bounce', views.bounce),
	#our class from views.py
	path('main', views.MainView.as_view()),
	path('remain/<slug:guess>', views.RestMainView.as_view()),
]

Request and Response Object

  • Django uses request and response objects to pass information throughout Django application.
  • When a page is requested by a browser, Django creates an HttpRequest object that contains metadata about the request.
  • Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object.
  • The Application Programming Interfaces (APIs) for HttpRequest and HttpResponse objects, are defined in the django.http module.

HTTP Location Header

  • You can send a “Redirect” response instead of a page response to communicate a “Location:” header to the browser
  • The location header includes a URL that the browser is supposed to forward itself to
  • It was originally used for web sites that moved form one URL to another

Sending a Redirect from a view

path('bounce', views.bounce)

from django.http import HttpResponse
from django.http import HttpResponseRedirect

#This is a command to the browser
def bounce(request):
	return HttpResponseRedirect('https://www.google.com/simple.htm')

Templates to organise HTML

Templates

  • Django generates HTML dynamically and conveniently by relying on templates.
  • A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted.
  • Django ships built-in backends for its own template system, creatively called the Django Template Language (DTL).
  • It is simply a text file which can be generated in any text-based format, containing variables and tags.

Template Render Process

Render Data + Template → Render Engine → Rendered Output

URL → View → Template

https://samples.dj4e.com/tmpl/game/200

path('game/<slug:guess>', views.GameView.as_view())

from django.shortcuts import render
from django.views import view

class GameView(View):
	def get(self, request, guess):
		x = {'guess':int(guess)}
		return render(request, 'tmpl/cond.html', x)

Templates in folders

  • It is common to reuse the “name” of a template in several applications
  • We use a technique called “namespace” so that each application can load its own templates
    • For the namespace to work, we need to put templates in a path that includes the application name twice.
      favs/templates/favs/detail.html
      favsql/templates/favsql/detail.html
      forums/templates/forums/detail.html
      pics/templates/pics/detail.html
    

Django Template Language (DTL)

Template Tags / Code

#Substitution

{{ zap }}
{{ zap | safe }}

#Calling code
{% url 'cat-detail' cat.id %}
{% author.get_absolute_url %}

#Logic
{% if zap > 100 %}
{% endif %}

#Blocks
{% block content %}
{% endblock %}

Template Inheritance

Inheritance

  • When we make a new template - we can extend an existing template and then add our own little bit to make our new class
  • Another form of store and reuse

Template Inheritance

Render Data + Base Template + Template → Render Engine → Rendered Output

Categories:

Updated: