0% found this document useful (0 votes)
21 views

FS Fist IA QB Ans

6th sem notes

Uploaded by

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

FS Fist IA QB Ans

6th sem notes

Uploaded by

Varun N
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

FULLSTACK IA-1 QUESTION BANK

MODULE-1
1. What is Django? Explain Django’s architecture. (or) Explain MVT Model
with neat diagram.
Django: One of the greatest frameworks for full stack web development is Django, which
is used by companies like Google, Instagram, YouTube, and NASA. It enables
programmers to rapidly construct online apps without having to worry about tasks like
creating HTML templates or database management. A template engine for producing
HTML views, an object-relational mapper (ORM) for communicating with databases, and
a multitude of tools and libraries for common tasks are all included in Django.

ARCHITECTURE: The architecture of almost all most popular web development


frameworks is based on the decomposition of several separate layers (applications,
modules, etc), which means that you can extend functionality according to your
requirements and integrate your changes with framework code, or use third-party
applications designed by external vendors. This flexibility is another key benefit of
frameworks. There are a lot of open-source communities and commercial organizations that
produce applications or extensions for popular frameworks e.g., Django REST Framework,
ng-bootstrap, etc.). The MVC – that is, a Model, View and Controller – are the three things
each web framework is made of. It is considered to be a basic structure, but there can be
several contrasts among them

MVT DESIGN PATTERN (MODEL VIEW TEMPLATE)


(Django follows the MVT model)
• Model - The data you want to present, usually data from a database.
• View - A request handler that returns the relevant template and content - based on the
request from the user.
• Template - A text file (like an HTML file) containing the layout of the web page, with
logic on how to display the data.

MODEL

• The model provides data from the database. The model contains all the data and
business logic layers, its rules and functions.
• In Django, the data is delivered as an Object Relational Mapping (ORM), which is a
technique designed to make it easier to work with databases.
• The most common way to extract data from a database is SQL. One problem with SQL
is that you have to have a pretty good understanding of the database structure to be able
to work with it.
• Django, with ORM, makes it easier to communicate with the database, without having
to write complex SQL statements.
• The models are usually located in a file called models.py. The models.py file contains
a description of the database table, as a Python class. This is called a model. Using this
class, you can create, retrieve, update, and delete records in your database using simple
Python code rather than writing repetitive SQL statements.

VIEWS
• The view, on the other hand, is responsible for all visual representations of data, like
diagrams, charts etc. A view is a function or method that takes http requests as
arguments, imports the relevant model(s), and finds out what data to send to the
template, and returns the final result.
• The views are usually located in a file called views.py. The views.py file contains the
business logic for the page.
• The urls.py file specifies which view is called for a given URL pattern.

TEMPLATE
• A template is a file where you describe how the result should be represent or describes
the design of the page
• Templates are often .html files, with HTML code describing the layout of a web page,
but it can also be in other file formats to present other results, but we will concentrate
on .html files.
• Django uses standard HTML to describe the layout
• The templates of an application is located in a folder named templates.

➢ 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).
➢ A key advantage of such an approach is that 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.
➢ For example, a developer can change the URL for a given part of the application without
affecting the underlying implementation. A designer can change a page’s HTML
without having to touch the Python code that renders it. A database administrator can
rename a database table and specify the change in a single place, rather than having to
search and replace through a dozen files.
2. Explain Django project directory structure.
3. How do you create a Django project and app?
4. Explain Django urls and views with an example.

5. What are the features available in Django Web framework?


A web framework is a software tool that provides a way to build and run web applications.
As a result, you don’t need to write code on your own and waste time looking for possible
miscalculations and bugs.
In the early days of web development, all applications were hand-coded, and only the
developer of a certain app could change or deploy it. Web frameworks introduced a simple
way out of this trap. Since 1995, all the hassle connected with changing an application’s
structure has been put in order because of the appearance of a general performance. And
that’s when web-specific languages appeared. Their variety is now working well for both
static and dynamic web pages.
A Web framework provides a programming infrastructure for your applications, so that you
can focus on writing clean, maintainable code without having to reinvent the wheel. In a
nutshell, that’s what Django does.

FEATURES
• Web Caching: Web caching simply helps store different documents and avoids
annoying phenomenon of the server overload. Users can use it in various systems if
several conditions are met. It also works on the server side. For example, you may
notice cached content links on the SERP (Search Engine Results Page) of a search
engine like Google.

• Scaffolding: This is another important technique to know and use, which is supported
by some MVC frameworks. Typical parts of application or the entire project structure
(in case of initialization) can be generated by the framework automatically. This
approach increases the speed of the development cycle and standardizes the codebase.

• Web template system: A web template system is a set of different methodologies and
software implemented to construct and deploy web pages. Template engines are used
to process web templates. They are a tool for web publishing in a framework.

• Security: Online security has plenty of criteria for identifying and permitting or
rejecting access to different functions in a web framework. It also helps recognize the
profiles that use the application to avoid clickjacking. As a result, the framework itself
is authentic and authorized.

• URL Mapping: If you want to simplify the indexing of your website by search engines
while creating a clear and eye-catching site name, this web frameworks’ feature is
custom-made for it. URL Mapping can also facilitate access to your sites’ URLs.

• Applications: Numerous types of web applications are supported by web frameworks.


The most common and best frameworks for app development support the construction
of blogs, forums, general-purpose websites, content management systems, etc.

6. Discuss about history of Django.


• Django was design and developed by Lawrence journal world in 2003 and publicly
released under BSD license in July 2005.
• Currently, DSF (Django Software Foundation) maintains its development and release
cycle.
• Django was released on 21, July 2005.
7. Explain the steps of installation of Django
STEP 1: PYTHON INSTALLATION
• Installing Python Django is written in 100% pure Python code, so you’ll need to install
Python on your system
• To check if your system has Python installed, run this command in the command
prompt: python --version

STEP 2: PIP INSTALLATION

• To install Django, you must use a package manager like PIP, which is included in
Python from version 3.4.
• To check if your system has PIP installed, run this command in the command prompt:
pip –version

STEP 3: SETTING VIRTUAL ENVIRONMENT


• It is suggested to have a dedicated virtual environment for each Django project, and one
way to manage a virtual environment is venv, which is included in Python.
• The name of the virtual environment is your choice, in this tutorial we will call it
myworld.
• Type the following in the command prompt, remember to navigate to where you want
to create your project:
➢ Windows: py -m venv myworld
➢ Unix/MacOS: python -m venv myworld

• Then you have to activate the environment, by typing this command:


➢ Windows: myworld\Scripts\activate.bat
➢ Unix/MacOS: source myworld/bin/activate

• Once the environment is activated, you will see this result in the command prompt:
➢ Windows: (myworld) C:\Users\Your Name>
➢ Unix/MacOS: (myworld) ... $

STEP 4: INSTALL DJANGO


• Now, that we have created a virtual environment, we are ready to install Django.
• Note: Remember to install Django while you are in the virtual environment!
• Django is installed using pip, with this command:
➢ Windows: (myworld) C:\Users\Your Name>py -m pip install Django
➢ Unix/MacOS: (myworld) ... $ python -m pip install Django
• Which will give a result that looks like this:

STEP 5: CHECK DJANGO VERSION


django-admin –version

STEP 6: DJANGO CREATE PROJECT


• A project is a collection of settings for an instance of Django, including database
configuration, Django-specific options, and application-specific settings.
• Create a directory by name djcode: mkdir djcode
• Once you have come up with a suitable name for your Django project, navigate to where
in the file system you want to store the code (in the virtual environment), I will navigate
to the folder, and run this command in the command prompt:
django-admin startproject mysite
• Django creates a mysite folder on my computer, with this content:

• These files are as follows:


__init__.py: A file required for Python; treat the directory as a package (i.e., a
group of modules).
manage.py: A command-line utility that lets you interact with this Django
project in various ways
settings.py: Settings/configuration for this Django project
urls.py: The URL declarations for this Django project; a “table of contents” of
your Django-powered sit

STEP 7: RUN THE DJANGO PROJECT

• Now that you have a Django project, you can run it, and see what it looks like in a
browser. In cmd prompt run “code .”, this will take to VS Code current project. Open
terminal in VS Code
• Navigate to the /mysite folder and execute this command in the command prompt:
py manage.py runserver
• Which will produce this result:

• Open a new browser window and type http://127.0.0.1:8000/ in the address bar.
• The result:

STEP 8: DJANGO CREATE APP


• An app is a web application that has a specific meaning in your project, like a home
page, a contact form, or a members database.
• Start by navigating to the selected location where you want to store the app, in my case
the mysite folder, and run the command below.
• If the server is still running, and you are not able to write commands, press [CTRL]
[BREAK], or [CTRL] [C] to stop the server and you should be back in the virtual
environment.
• Creation of app should be done in VS Code terminal only:
py manage.py startapp members
8. Write a Django application that returns the current date & time as an
HTML document.

9. How to map urls to views? Explain with an example.


DANJO 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.
• A web page that uses Django is full of views with different tasks and missions.
• Views are usually put in a file called views.py located on your app's folder.

• STEPS TO CREATE VIEWS:


➢ First create a file called views.py in the mysite directory. (right click on the folder
mysite in VS CODE – new file – give file name as views.py)
➢ view that returns the current date and time, as an HTML document:

First, we import the class HttpResponse, which lives in the django.http


module.
The datetime module contains several functions and classes for dealing with
dates and times, including a function that returns the current time.
Next, we define a function called current_datetime. This is the view function.
Each view function takes an HttpRequest object as its first parameter, which
is typically named request.
The first line of code within the function calculates the current date/time as a
datetime. datetime object, and stores that as the local variable now.
The second line of code within the function constructs an HTML response
using Python’s format-string capability. The %s within the string is a
placeholder, and the percent sign after the string means “Replace the %s with
the value of the variable now.”
Finally, the view returns an HttpResponse object that contains the generated
response. Each view function is responsible for returning an HttpResponse
object.

MAPPING URLS TO VIEWS


• A URLconf is like a table of contents for your Django-powered Web site. Basically, it’s
a mapping between URL patterns and the view functions that should be called for those
URL patterns. It’s how you tell Django, “For this URL, call this code, and for that URL,
call that code .”
• When we executed django-admin.py startproject. The script created a URLconf for
you automatically: the file urls.py. Let’s edit that file:
• When a user requests a page from your Django-powered site, this is the algorithm the
system follows to determine which Python code to execute:
Django determines the root URLconf module to use. Ordinarily, this is the value of
the ROOT_URLCONF setting, but if the incoming HttpRequest object has a
urlconf attribute (set by middleware), its value will be used in place of the
ROOT_URLCONF setting.
Django loads that Python module and looks for the variable urlpatterns. This should
be a sequence of django.urls.path() and/or django.urls.re_path() instances.
Django runs through each URL pattern, in order, and stops at the first one that
matches the requested URL, matching against path_info.
Once one of the URL patterns matches, Django imports and calls the given view,
which is a Python function (or a class-based view). The view gets passed the
following arguments:
➢ An instance of HttpRequest.
➢ If the matched URL pattern contained no named groups, then the matches from
the regular expression are provided as positional arguments.
➢ The keyword arguments are made up of any named parts matched by the path
expression that are provided, overridden by any arguments specified in the
optional kwargs argument to django.urls.path() or django.urls.re_path().
If no URL pattern matches, or if an exception is raised during any point in this
process, Django invokes an appropriate error-handling view.

10. How does Django process a request. Explain with a neat diagram.
• The command python manage.py runserver imports a file called settings.py from the
same directory. This file contains all sorts of optional configuration for this particular
Django instance.
• The ROOT_ URLCONF setting tells Django which Python module should be used as
the URLconf for this Web site.
• The view function is responsible for returning an HttpResponse object.

• When an HTTP request comes in from the browser, a server-specific handler constructs
the HttpRequest passed to later components and handles the flow of the response
processing.
• The handler then calls any available Request or View middleware. These types of
middle ware are useful for augmenting incoming HttpRequest objects as well as
providing special handling for specific types of requests. If either returns an
HttpResponse, processing bypasses the view.
• If a view function raises an exception, control passes to the exception middleware. If
this mid dleware does not return an HttpResponse, the exception is reraised.
• Even then, all is not lost. Django includes default views that create a friendly 404 and
500 response. Finally, response middleware is good for postprocessing an
HttpResponse just before it’s sent to the browser or doing cleanup of request-specific
resources.
11. Construct the wild card patterns with an examples.
• view example, the contents of the page—the current date/time—were dynamic, but the
URL (/time/) was static. In most dynamic Web applications, though, a URL contains
parameters that influence the output of the page.
• Let’s create a second view that displays the current date and time offset by a certain
number of hours.
• URLconf like this:

• let’s put a wildcard in the URLpattern, a URLpattern is a regular expression; hence, we


can use the regular expression pattern \d+ to match one or more digits:
• request is an HttpRequest object, just as in current_datetime.
• each view always takes an HttpRequest object as its first parameter.
• offset is the string captured by the parentheses in the URL pattern. For example, if the
requested URL were /time/plus/3/, then offset would be the string '3'. If the requested
URL were /time/plus/21/, then offset would be the string '21'. Note that captured strings
will always be strings, not integers, even if the string is composed of only digits, such
as '21'
• function int() on offset. This converts the string value to an integer. Python will raise a
ValueError exception if you call int() on a value that cannot be converted to an integer,
such as the string 'foo'. (\d{1,2})—captures only digits.
• construct the HTML output of this view function uses Python’s format-string capability
with two values, two %s symbols in the string and a tuple of values to insert:
(offset, dt)
• return an HttpResponse of the HTML
• start the Django development server (if it’s not already running), and visit
http://127.0.0.1:8000/time/plus/3/ to verify it works.
Then try:
http://127.0.0.1:8000/time/plus/5/.
http://127.0.0.1:8000/time/plus/24/.
http://127.0.0.1:8000/time/plus/100/
• pattern in your URLconf only accepts one- or two-digit numbers; Django should
display a“Page not found” error in this case, just as we saw in the “404 Errors” section
earlier. The URL http://127.0.0.1:8000/time/ plus/ (with no hour designation) should
also throw a 404.
• comment out the offset = int(offset) line in the hours_ahead view: TypeError
message displayed at the very top: "unsupported type for timedelta hours
component: str". datetime.timedelta function expects the hours parameter to be an
integer, and we commented out the bit of code that converted offset to an integer. That
caused datetime.timedelta to raise the TypeError.

12. Discuss the path converter available in Django.


The following path converters are available by default:
• str - Matches any non-empty string, excluding the path separator, '/'. This is the default
if a converter isn’t included in the expression.
• int - Matches zero or any positive integer. Returns an int.
• slug - Matches any slug string consisting of ASCII letters or numbers, plus the hyphen
and underscore characters. For example, building-your-1st-django-site.
• uuid - Matches a formatted UUID. To prevent multiple URLs from mapping to the
same page, dashes must be included and letters must be lowercase. For example,
075194d3-6885-417ea8a8-6c931e272f00. Returns a UUID instance.
• path - Matches any non-empty string, including the path separator, '/'. This allows you
to match against a complete URL path rather than a segment of a URL path as with str.
• If the paths and converters syntax isn’t sufficient for defining your URL patterns, you
can also use regular expressions. To do so, use re_path() instead of path().

13. Explain the principle of 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.
• In a Django Web application, the URL definitions and the view functions are loosely
coupled; that is, the decision of what the URL should be for a given function, and the
implementation of the function itself, reside in two separate places. This lets a developer
switch out one piece without affecting the other.
• For example, consider the view function we wrote earlier, which displays the current
date and time. If we wanted to change the URL for the application— say, move it from
/time/ to /currenttime/—we could make a quick change to the URLconf, without
having to worry about the underlying implementation of the function. Similarly, if we
wanted to change the view function—altering its logic somehow—we could do that
without affecting the URL to which the function is bound.

(OR)

• Loose coupling is a software design principle that promotes independence and


modularity by minimizing the dependencies between different components of a system.
In the context of Django, loose coupling is achieved through:
Separation of Concerns: Django encourages the separation of concerns by
dividing an application into distinct components, such as models, views, templates,
and URLconfs. Each component has a specific responsibility and interacts with
other components through well-defined interfaces.
Decoupled URLs and Views: In Django's URL routing system, views are
decoupled from URLs. Views are Python functions or class-based views that
encapsulate the logic for processing requests and generating responses. URLconfs
define the mapping between URLs and views but do not directly reference the view
functions themselves.
Dependency Injection: Django's design promotes dependency injection, allowing
components to be loosely coupled by injecting dependencies rather than directly
instantiating them. For example, views can accept parameters representing
dependencies such as models, forms, or services, making them easier to test and
reuse.
Pluggable Applications: Django's app-based architecture encourages the
development of pluggable, reusable applications that can be easily integrated into
different projects. By providing well-defined APIs and extension points, Django
promotes loose coupling between applications, enabling greater flexibility and
scalability.
MODULE-2

1. What are templates in Django? (or) Explain basic template system.


TEMPLATE SYSTEM BASICS
HTML was hard-coded directly in our Python code. This arrangement leads to several
problems:
• Any change to the design of the page requires a change to the Python code. The design
of a site tends to change far more frequently than the underlying Python code, so it
would be convenient if the design could change without needing to modify 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 even separate departments). Designers and HTML/CSS coders
shouldn’t have to edit Python code to get their job done; they should deal with HTML.
• Similarly, it’s most efficient if programmers can work on Python code and designers
can work on templates at the same time, rather than one person waiting for the other to
finish editing a single file that contains both Python and HTML. For these reasons, it’s
much cleaner and more maintainable to separate the design of the page from the Python
code itself. We can do this with Django’s template system.

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.
• Let’s dive in with a simple example template. This template describes an HTML page
that thanks a person for placing an order with a company. Think of it as a form letter:
Templates
• A template is a text file. It can generate any text-based format (HTML, XML, CSV,
etc.).
• A template contains variables, which get replaced with values when the template is
evaluated, and tags, which control the logic of the template.

Variables
• Variables look like this: {{ variable }}. When the template engine encounters a
variable, it evaluates that variable and replaces it with the result. Variable names consist
of any combination of alphanumeric characters and the underscore ("_") but may not start
with an underscore, and may not be a number. The dot ( ".") also appears in variable
sections, although that has a special meaning.
• Any text surrounded by a pair of braces (e.g., {{ person_name }}) is a variable. This
means “insert the value of the variable with the given name.”
Tags
• Tags look like this: {% tag %}. The definition of a tag is quite broad: a tag just tells
the template system to “do something.” Tags are more complex than variables: Some
create text in the output, some control flow by performing loops or logic, and some load
external information into the template to be used by later variables.
• Some tags require beginning and ending tags
(i.e. {% tag %} ... tag contents ... {% endtag %}).
• Django ships with about two dozen built-in template tags.
• Any text that’s surrounded by curly braces and percent signs (e.g., {% if
ordered_warranty %}) is a template tag.
• This example template contains two tags: the {% for item in item_list %} tag (a for
tag) and the {% if ordered_warranty %} tag (an if tag)
Filters
• Django Template Engine provides filters which are used to transform the values of
variables and tag arguments. Tags can’t modify value of a variable whereas filters can
be used for incrementing value of a variable or modifying it to one’s own need. Filters
can be “chained.” The output of one filter is applied to the next.
• Syntax {{ variable_name | filter_name }}

• The second paragraph of this template has an example of a filter, with which you can
alter the display of a variable. In this example, {{ ship_date|date:"F j, Y" }}, we’re
passing the ship_date variable to the date filter, giving the date filter the argument "F
j, Y". The date filter formats dates in a given format, as specified by that argument.
Filters are attached using a pipe character (|), as a reference to Unix pipes.

2. Steps in creating a template object using interpreter. (or) How do you use
template system in python code?
USING THE TEMPLATE SYSTEM
• To use the template system in Python code, just follow these two steps:
➢ Create aTemplateobject by providing the raw template code as astring.
Django also offers away to create Templateobjects by designating the path to
atemplate file on the filesystem; we’ll examine that in abit.
➢ Call the render()method of the Templateobject with agiven set of variables
(i.e., the context). This returns afully rendered template as astring, with all of
the variables and block tags evaluated according to the context.

Creating Template Objects


• create a Templateobject is to instantiate it directly. The Templateclass lives in the
django.templatemodule, and the constructor takes one argument, the raw template
code.
• Multiline statements in the interactive interpreter are padded with three dots (...)
• Execute the shell interpreter in VSCode terminal

• After starting the interactive interpreter:


• When you create a Template object, the template system compiles the raw template
code into an internal, optimized form, ready for rendering. But if your template code
includes any syntax errors, the call to Template() will cause a TemplateSyntaxError
exception:

The system raises a TemplateSyntaxError exception for any of the following cases:
• Invalid block tags
• Invalid arguments to valid block tags
• Invalid filters • Invalid arguments to valid filters
• Invalid template syntax
• Unclosed block tags (for block tags that require closing tags)

Rendering a Template

• Django provides the Template and Context classes to represent the string template
being rendered and the data being used during generation. The Context class is a
wrapper to a dict and provides key-value pairs to populate the generated content. The
result of a rendered template can be any text but is frequently HTML. Django is a web
framework, after all.
• Once you have a Template object, you can pass it data 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.
• A context is represented in Django by the Context class, which lives in the
django.template module. Its constructor takes one optional argument: a dictionary
mapping variable names to variable values. Call the Template object’s render() method
with the context to “fill” the template:
• Dictionaries and Contexts A Python dictionary is a mapping between known keys and
variable values.
• Variable names must begin with a letter (A-Z or a-z) and may contain digits,
underscores, and dots. (Dots are a special case we’ll get to in a moment.) Variable names
are case sensitive.

Let’s step through this code one statement at a time:


• First, we import the classes Template and Context, which both live in the module
django.template.
• We save the raw text of our template into the variable raw_template. Note that we use
triple quote marks to designate the string, because it wraps over multiple lines; in Python
codde, strings designated with single quote marks cannot be wrapped over multiple lines.
• Next, we create a template object, t, by passing raw_template to the Template class
constructor.
• We import the datetime module from Python’s standard library, because we’ll need it in
the following statement. Then, we create a Context object, c.
• The Context constructor takes a Python dictionary, which maps variable names to values.
Here, for example, we specify that the person_name is 'John Smith', product is 'Super
Lawn Mower', and so forth.
• Finally, we call the render() method on our template object, passing it the context. This
returns the rendered template—that is, it replaces template variables with the actual
values of the variables, and it executes any block tags.
• warranty paragraph was displayed because the ordered_warranty variable evaluated to
True. Also note the date, April 2, 2009, which is displayed according to the format string
'F j, Y'
Multiple Contexts, Same Template

• Once you have a Template object, you can render multiple contexts through it.
• Whenever you’re using the same template source to render multiple contexts like this,
it’s more efficient to create the Template object once, and then call render() on it multiple
times:

3. Explain the context variable lookups with an example.


Context Variable Lookup

• Variable names must consist of any letter (A-Z), any digit (0-9), an underscore (but they
must not start with an underscore) or a dot.
• Dots have a special meaning in template rendering. A dot in a variable name signifies
a lookup. Use a dot to access dictionary keys, attributes, indices, or methods of an object
• To access the values of that dictionary by dictionary key, use a dot:

• dots also allow access of object attributes. For example, a Python datetime.date object
has year, month, and day attributes, and you can use a dot to access those attributes in a
Django template:
• This example uses a custom class:

• Dots are also used to call methods on objects. Python string has the methods upper() and
isdigit(), and you can call those in Django templates using the same dot syntax:

• Dots are also used to access list indices, negative list indices are not allowed. For
example, the template variable {{items.-1}} would cause a TemplateSyntaxError for
example:

• Dot lookups can be nested multiple levels deep


• When the template system encounters a dot in a variable name, it tries the following
lookups, in this order:
• Dictionary lookup (e.g., foo["bar"])
• Attribute lookup (e.g., foo.bar)
• Method call (e.g., foo.bar())
• List-index lookup (e.g., foo[bar])
Method Call Behavior
• If, during the method lookup, a method raises an exception, the exception will be
propagated, unless the exception has an attribute silent_variable_failure whose value
is True. If the exception does have a silent_variable_failure attribute, the variable will
render as an empty string

• A method call will only work if the method has no required arguments. Otherwise, the
system will move to the next lookup type (list-index lookup).

How Invalid Variables Are Handled


• if a variable doesn’t exist, the template system renders it as an empty string, failing
silently, for example:
• The system fails silently rather than raising an exception because it’s intended to be
resilient to human error.
• In this case, all of the lookups failed because variable names have the wrong case or
name. In the real world, it’s unacceptable for a Web site to become inaccessible due to a
small template syntax error.

Playing with Context Objects

• Add and delete items from a Context object once it’s been instantiated, too, using
standard Python dictionary syntax:
4. Explain ‘if’ tag with an example.
Tags:
• The templates tags are a way of telling Django that here comes something else than plain
HTML.
• The template tags allow us to do some programming on the server before sending HTML
to the client.
• Tags are like the template language’s keywords and functions. In Python, keywords and
functions provide control flow and tools your code is built upon.
• Templates should be added in settings file in the project:
'DIRS': [BASE_DIR,"templates"],

5. Explain ‘for’ tag with an example. (or) Outline the statement “The
{%for%} tag sets a magic for loop templates variable within the loop”.
The {%for%} tag allows you to loop over each item in a sequence. As in Python’s for
statement, the syntax is for X in Y, where Y is the sequence to loop over and X is the name
of the variable to use for a particular cycle of the loop. Each time through the loop, the
template system will render everything between {%for%} and {%endfor%}.

Add reversed to the tag to loop over the list in reverse:

• There is no support for “breaking out” of a loop before the loop is finished. If you want
to accomplish this, change the variable you’re looping over so that it includes only the
values you want to loop over. Similarly, there is no support for a “continue” statement
that would instruct the loop processor to return immediately to the front of the loop.
• The {% for %} tag sets a magic forloop template variable within the loop. This variable
has a few attributes that give you information about the progress of the loop:
forloop.counter is always set to an integer representing the number of times the
loop has been entered. This is one-indexed, so the first time through the loop,
forloop.counter will be set to 1.

forloop.counter0 is like forloop.counter, except it’s zero-indexed. Its value will be


set to 0 the first time through the loop.

forloop.revcounter is always set to an integer representing the number of


remaining items in the loop. The first time through the loop, forloop.revcounter
will be set to the total number of items in the sequence you’re traversing. The last
time through the loop, forloop.revcounter will be set to 1
forloop.revcounter0 is like forloop.revcounter, except it’s zero-indexed. The first
time through the loop, forloop.revcounter0 will be set to the number of elements
in the sequence minus 1. The last time through the loop, it will be set to 0.
forloop.first is a Boolean value set to True if this is the first time through the loop.
This is convenient for special casing:

forloop.last is a Boolean value set to True if this is the last time through the loop.
A common use for this is to put pipe characters between a list of links:

forloop.parentloop is a reference to the forloop object for the parent loop, in case
of nested loops.
6. Create a two list athletic list and coach-list. Illustrate the ‘if’ tag on the
lists created.
if/else
• The {% if %} tag evaluates a variable, and if that variable is “true” (i.e., it exists, is not
empty, and is not a false Boolean value), the system will display everything between {%
if %} and {% endif %},
• for example:

• In Python, the empty list ([]), tuple (()), dictionary ({}), string (''), zero (0), and the
special object None are False in a Boolean context. Everything else is True.
• The {% if %} tag accepts and, or, or not for testing multiple variables, or to negate a
given variable.
• For example:
• {% if %} tags don’t allow and and or clauses within the same tag, because the order of
logic would be ambiguous.
• For example, this is invalid: {% if athlete_list and coach_list or
cheerleader_list %}
• if you need to combine and and or to do advanced logic, just use nested {% if %} tags,
for example:

• There is no {% elif %} tag. Use nested {% if %} tags to accomplish the same thing:

• Make sure to close each {% if %} with an {% endif %}. Otherwise, Django will throw
a TemplateSyntaxError.

You might also like