0% found this document useful (0 votes)
77 views28 pages

Full Stack Web Development with Django

The document discusses full stack web development using the Django framework. It covers topics like MVC architecture, template inheritance, generic views, and jQuery integration with Django apps to build responsive full stack applications.

Uploaded by

vaishuteju12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views28 pages

Full Stack Web Development with Django

The document discusses full stack web development using the Django framework. It covers topics like MVC architecture, template inheritance, generic views, and jQuery integration with Django apps to build responsive full stack applications.

Uploaded by

vaishuteju12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

FULLSTACK DEVELOPMENT

(21CS62)
VI SEM CSE
Course Learning Objectives:
CLO [Link] the use of learning full stack web development.

CLO [Link] use of rapid application development in the


design of responsive web pages.

CLO [Link] Models, Views and Templates with their


connectivity in Django for full stack web development.

CLO [Link] the use of state management and admin


interfaces automation in Django.

[Link] and implement Django apps containing dynamic


pages with SQL databases.
Course outcome
CO1. Understand the working of MVT based full stack
web development with Django.
CO2. Designing of Models and Forms for rapid
development of web pages.
CO3. Analyze the role of Template Inheritance and
Generic views for developing full stack web applications.
CO4. Apply the Django framework libraries to render non
HTML contents like CSV and PDF.
CO5. Perform jQuery based AJAX integration to Django
Apps to build responsive full stack web applications
Module-1: MVC based Web Designing
 Web Framework
A Web framework provides a programming infrastructure for
web applications, so that the programmer can focus on writing
clean, maintainable code without having to reinvent the wheel.
 Model-View-Controller (MVC)
MVC defines a way of developing software so that the code for
defining and accessing data (the model) is separate from request
routing logic (the controller), which in turn is separate from the
user interface (the view). The MVC components are loosely
coupled. That is, each distinct piece of a Django-powered Web
application has a single key purpose and can be changed
independently without affecting the other pieces.
Separation of concern
1. The [Link] file contains a description of the
database table, as a Python class.
2. The [Link] file contains the business logic for the
page.
3. The [Link] file specifies which view is called for a
given URL pattern.
4. HTML template that describes the design of the
page.
The MVC Design pattern
//[Link]
from [Link] import models
class book([Link]):
name=[Link](max_length=250)

//[Link]
from [Link] import render
from . models import book
def bookinfo (request):
booklist=[Link]();
return render(request,’[Link]’,{‘booklist’:booklist})
The MVC Design pattern
//[Link]
import views
from [Link] import path
urlpatterns=[
Path(‘latest/ ’,[Link], name=‘[Link]’)
]
//[Link]
<html>
<body>
<ul>
{% for book in booklist%}
<li>{{[Link]}}</li>
{% endfor%}
</ul></body></html>
Django Evolution
 Django grew organically from real-world applications written
by a Web development team in Lawrence, Kansas. It was born
in the fall of 2003, when the Web programmers at the
Lawrence Journal-World newspaper, Adrian Holovaty and
Simon Willison, began using Python to build applications.
 In July 2005 it is released as Django, after the jazz guitarist
Django Reinhardt.
 Sweet spot and and open source
View function
 A view function is simply a Python function that takes a
Web request and returns a Web response.
//[Link]
from [Link] import HttpResponse
import datetime
def current_datetime(request):
now = [Link]()
html = “<html><body> It is now %s.</body></html>%now
return HttpResponse(html)
View function
 The HttpResponse, which lives in the [Link] module.
 The datetime module is imported from Python’s standard
library.
 The current_datetime is the view function. Each view
function takes an HttpRequest object as its first parameter.
 The value of datetime is stored in local variable now.
 An HTML response is constructed using Python’s format-
string capability.
 The view returns an HttpResponse object that contains the
generated response.
Mapping URL to view
 It is a mapping between URL patterns and the view functions
that should be called for those URL patterns.
 By default, the [Link] looks like
from [Link] import admin
from [Link] import path
from program1_app import views
urlpatterns = [
path('admin/', [Link]),
// path('',views. current_datetime)
]
 The url patterns save the wanted urls of the views. This
variable defines the mapping between URLs and the code
that handles those URLs. It is expected to be found in
ROOT_URLCONF module.
Working of Django URL Confs and Loose Coupling
 Loose coupling is a software-development approach that values
the importance of making pieces interchangeable. If two pieces of
code are loosely coupled, then changes made to one of the pieces
will have little or no effect on the other.
 If wanted to change the URL for the application— say, move it
from /time/ to /currenttime/—could make a quick change to the
URLconf, without having to worry about the underlying
implementation of the function. Similarly, if wanted to change the
view function—altering its logic somehow— could do that
without affecting the URL to which the function is bound. If
wanted to expose the current-date functionality at several URLs,
could easily take care of that by editing the URLconf, without
having to touch the view code.
Errors in Django

 Django displays the error message when the requested URL


that’s not defined in URLconf.
 Django tells which URLconf django used and every patterns
in the URLconf.
 The “Page not found” page is only displayed only the Django
is in debug mode. Every Django project is in debug mode
when first create it, and if the project is not in debug mode a
different response is given.
Wild Card patterns in URLS.

 A URLpattern is a regular expression; hence user can use it.


Te regular expression pattern \d+ is used to match one or
more digits:
 from [Link] import*
from [Link] import current_datetitmte, ahead
urlpatterns[
path(‘time/’,current_datetime),
path(‘time/plus/\d+/’,ahead)
]
 It is possible to allow either one- or two-digit numbers—
in regular expression using \d{1,2}.
Module-2: The Django Template System
 Challenges
It is much cleaner and more maintainable to separate the design of the
page from the Python code, otherwise Any change to the design of the
page requires a change to the Python code. Writing Python code and
designing HTML are two different disciplines, and most professional
Web development environments split these responsibilities between
separate people or departments. The most efficient programmers can
work on Python code and designers can work on templates at the
same time.
Template System Basics
 A Django template is a string of text that is intended to separate the
presentation of a document from its data. A template defines
placeholders and various bits of basic logic (i.e., template tags)
that regulate how the document should be displayed. Usually,
templates are used for producing HTML, but Django templates are
equally capable of generating any text-based format.

1. Any text surrounded by a pair of braces (e.g., {{ person_name }}) is a


variable.
2. Any text that’s surrounded by curly braces and percent signs (e.g., {% if
ordered_ warranty %}) is a template tag.
3. The filters, can be used to alter the display of a variable.
Template System Basics
<html>
<body>
<p>Dear {{personname}}</p>
<p>Thanks from {{companyname}}</p>
<p>The shopping cart</p>
<ul>
{% for item in item_list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
Using the Template System
 Create a Template object by providing the raw template code as a
string. Django also offers a way to create Template objects by
designating the path to a template file on the file system.
 Call the render() method of the Template object with a given set of
variables (i.e., the context). This returns a fully rendered template
as a string, with all of the variables and block tags evaluated
according to the context.
Creating Template Objects
 The easiest way to create a Template object is to instantiate it
directly. The Template class lives in the [Link] module,
and the constructor takes one argument, the raw template code.
from [Link] import Template
t = Template("My name is {{ name }}")
print t
 If the template code includes any syntax errors, the call to
Template() will cause a TemplateSyntaxError exception.
from [Link] import Template
t = Template(‘{% notatag %}’)
print t
Rendering a Template
 It is possible to pass the data of a Template object by giving it a
context. A context is simply a set of variables and their associated
values. A template uses this to populate its variable tags and
evaluate its block tags.

from [Link] import Context, Template


t = Template("My name is {{ name }}.")
c = Context({"name": "Stephane"})
[Link](c)
Template compilation and rendering
 The Django template system includes write a template, create a
Template object, create a Context, and call the render() method.
from [Link] import Context, Template
rawtemplate=“””<p>Dear {{name}}</p>”””
t = Template(rawtemplate)
c = Context({"name": "Stephane"})
[Link](c)
Basic template tags and filters
 Tags
 if/else e.g {% if today_is_weekend %}
 for e.g {% for athlete in athlete_list %}
 ifequal/ifnotequal e.g {% ifequal user currentuser %}
Welcome!
{% endifequal %}
 Comments-The comment will not be output when the template is
rendered, e.g. {# This is a comment #}.
 Filters-The template filters are simple ways of altering the value of
variables before they’re displayed, e.g. {{ name|lower }}.
 addslashes-Adds a backslash before any backslash, single quote, or double quote
 date-Formats a date or datetime object according to a format string given in the
parameter.
 escape-Escapes ampersands, quotes, and angle brackets in the given string.
 length-Returns the length of the value.
Template Loading
During template loading in Django, Pick a directory where user
would like to store the templates and add it to
TEMPLATE_DIRS, like so:
TEMPLATE_DIRS = ( '/home/django/mysite/templates', )
Django settings files are just Python code by constructing the
contents of TEMPLATE_DIRS dynamically.
import [Link]
TEMPLATE_DIRS = [Link](“BASE_DIR”,“templates”)
It is possible to change the view code to use Django’s template
loading functionality rather than hard-coding the template paths.
The function [Link].get_template() is used to
rather than loading the template. The get_template() function
takes a template name as its argument, figures out where the
template lives on the file system, opens that file, and returns a
compiled Template object.
Template Loading
render_to_response()
render_to_respons is a shortcut function to load a template, fill a
Context, and return an HttpResponse object with the result of the
rendered template.
from [Link] import render_to_response
import datetime
def current_datetime(request):
now = [Link]()
return render_to_response('current_datetime.html', {'current_date': now})

The first argument to render_to_response() should be the name of


the template to use. The second argument, if given, should be a
dictionary to use in creating a Context for that template.
Template Loading
The locals() Trick
It returns a dictionary mapping of all local variable names to
their values.
from [Link] import render_to_response
import datetime
def current_datetime(request):
Current_date = [Link]()
return render_to_response('current_datetime.html', locals())
Subdirectories in get_template()
In calls to get_template(), just include the subdirectory name
and a slash before the template name.
t = get_template('dateapp/current_datetime.html‘)
Template Loading
The include Template Tag
This include tag allows to include the contents of another template.
The argument to the tag should be the name of the template to
include, and the template name can be either a variable or a hard-
coded string.

{% include '[Link]' %}
{% include 'includes/[Link]' %}
{% include template_name %}
Template Inheritance
The template inheritance lets to build a base “skeleton” template
that contains all the common parts of the site and defines
“blocks” that child templates can override. The server-side
include solution to this problem is to factor out the common bits
in both templates and save them in separate template snippets,
which are then included in each template.
<html>
<body>
{% block content %}
hello
{% endblock %}
{% block footer %}
Thanks for visiting my site.
{% endblock %}
</body>
</html>
Template Inheritance
The child template can use the base template blocks as it’s own.
For example for current date html is given as

{% extends "[Link]" %}
{% block content %}
<p>It is now {{ current_date }}</p>
{% endblock %}

{% extends "[Link]" %}
{% block content %}
<p> {{ next_time }}</p>
{% endblock %}

You might also like