FS Fist IA QB Ans
FS Fist IA QB Ans
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.
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.
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.
• 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
• Once the environment is activated, you will see this result in the command prompt:
➢ Windows: (myworld) C:\Users\Your Name>
➢ Unix/MacOS: (myworld) ... $
• 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:
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:
(OR)
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.
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.
• 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:
• 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:
• 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).
• 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%}.
• 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.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.