django tutorial

Django-Home

Django is a python framework for developing web/ web applications. It is used in building and maintaining web applications. It is also used to develop a fast, scalable and secure website. A framework is essentially a library of reusable modules. These modules provide functionalities to perform common tasks. For example in the case of a web framework like Django, we have modules to work with HTTP requests, URLs, sessions, cookies, etc. So all this functionality is already provided into Django, we don’t have to code it from scratch, that is why we use a framework like Django. A framework also defines a structure for our applications. So it provides consistency among various Django projects.

Django–Basics

Django is a high-level Python web development framework that provides fast development and flexible, clean, realistic design. Hence, Django provides an easy environment to build better web apps quickly and with less code.

Advantages of Django Framework

i. Batteries included: 

Django provides itself as a batteries-included framework. It means it comes with a lot of packages build in out of the box, depending on your application you may use it. Instead of writing your own code (power), you just need to import the packages or module that you want to use.

It is a part of the protocol over configuration paradigm that Django is part of, and it allows you to make use of the implementation of the solution. 

Django batteries provide a wide range of contents that include:

  • Authentication users with auth package 
  • Admin Control with admin package 
  • Sessions management with Sessions package 
  • Show or manage Messages with Messages package 
  • Generate Google site map with Sitemaps package 
  • Postgres features with Postgres package 
  • Hooking with content types framework 

ii. Python:

As we know Django uses Python, it anchorages some of the power of python to its own benefit. Python is one of the easiest, flexible and dynamic programming language to learn for beginners, and it is also one of the most popular programming languages.

Python makes code shorts and easy to write.

iii. Community:

Django also provide a huge community and it is one of the best things about it, they are helpful and actively working on making the framework more beginners friendly and stabilizing the framework while adding new features. Django documentation is quite easy to go through and is useful as a standalone tutorial, it will help you wrap your head around various features so you can use it as a primary source of information. 

iv. Scalable:

Most of the developers, while thinking about picking up a framework plan for the future in their preference. That why while choosing a scalable framework is quite essential for many and Django is just that. It allows you to take a lot of various actions regarding scalability, such as running a separate web server for the database, the media, and the applications themselves or even use clustering or load balancing to distribute the applications across multiple web servers.

v. Built-in Admin Module:

The Django team was quite attentive when they creating the framework, and also they kept focus on user and client satisfaction. It is quite not logical to create your own admin panel interface at the backend which is just to be able to manage your data with basic Create, Read, Update, and Delete (CRUD) operations. That’s why Django offers a built-in administrative interface right out of the box that is both professional and versatile, according to the Django documents the web developer can now develop with the presentation in mind.

Disadvantages of Django Framework

Django is an amazing and powerful framework, but then also it consists of a few cons that may or may not be an issue for you.

  • URL specifying with regular expressions is not an easy task to manage, at least for beginners.
  • It also feels a little enlarged for small projects, and some people find it quite populated with big projects since models, for example, are all included in a single file. 
  • Template errors fail silently and it won’t show any error messages by default, so if you don’t know about that, then you may waste a lot of time trying to figure out about errors in the application, or even worse, you might not even know that your application has suffered from a problem.
  • It is also a strongly assertive framework, which gives it a rigid or inflexible feeling. Also, there is a popular and advised way of completing things and you were supposed to follow it.

Django–Overview

Django is an MVT web framework that is used to build web apps. It defines itself as a “batteries included” web framework, with stability and simplicity to help developers to write clean, efficient and powerful code. It is one of the most famous web frameworks used by web developers and it is also one of the most used frameworks as well. It is used to develop popular web apps like  Instagram, Youtube, Spotify, Google and even NASA for their website. So let break down even more further to learn more about it.

Django works on MVT architecture which stands for Models Views Templates. MVT is a Django framework is a variation of the famous MVC structure which stands for Model View Control, that why you will feel it’s quite analogous to how other frameworks work. When the Django server receives a request, the URL rout and maps the request to the appropriate views. The view then fetches the response through the models, fill the template and send it back to the users. The web developer just provides the models, the view and the template and then just maps it to the main URL which is located in urls.py files and for the rest, Django does the magic to show or serve it to the users.

Django–Environment

Django is a python framework so for setting up over Django environment we must require first a python language. So we need to install the latest version of python on our system. Either we directly go for installing python3 or else we need Python 2.6.5 or a higher one.

Step 1 – Installing Latest Python:

  • Download Python Link: https://www.python.org/downloads/
  • If you want to check the python version or it is previously installed in your system so just open the terminal/command prompt and just type python or python3.

Syntax: python

Code:

linux@root: ~$ python3

Python 3.8.5 (default, Jan 27 2021, 15:41:15) 

[GCC 9.3.0] on linux

>>> | “

Step 2 – Creating Virtual Environment (venv):

A virtualenv is a tool for creating an insulated virtual python environment for python projects. To develope virtual environment we need to install first and than we need to activate virtual environment.

To install: “ pip install virtualenv ”

To create and activate virtualenv: 

Syntax: virtualenv <virtualenv_name> 

Code:

linux@root:~/django_project/CellShop$ virtualenv venv

linux@root:~/django_project/CellShop$ . venv/bin/activate

(venv) linux@root:~/django_project/CellShop$ ”

Step 3 – Installing Django:

For easy installation of Django, we used the pip installer package. pip is a Python package installer which is used to manage and install python software packages. We can install several python modules easily using pip. 

Syntax: pip install <module_name>

Code:    “ (venv) linux@root:~/django_project/CellShop$  pip install Django==3.2”

Django Latest Version Downloading Link: https://www.djangoproject.com/download/

Step 4 – Django Database:

By default Django support SQLite3  database. But Django also supports various others database engines like MySQL, Oracle, PostgreSQL, etc and you can easily set up any of them based on your requirement.

Step 5 – Django WebServer:

Django contains a lightweight web server for creating and testing our web applications. This webserver is pre-configured to work on the Django framework, and it restarts the webserver whenever you modify the app code.

Django also creates wsgi.py files while creating our Django projects. WSGI stands for web server gateway interface The purpose of this module is to provide a standard interface between applications built with Django and web servers. 

Django supports Apache webserver and also other popular web servers. On our local system by default mostly Django run on 8000 port i.e  127.0.0.1:8000 or localhost:8000 and http://127.0.0.1:8000/.

Django – Creating a Project:

Now we have successfully installed Django on our systems, let us start creating our project using the Django framework. In Django, all the web app you have created is known as a project and a project is an additions of applications. An application is a set of programs files that are implemented based on the Model-View-Templates (MVT) pattern. For example let say we want to create an e-commerce website, the website is our Django project and, the products, accounts, carts engine are applications. So for that, this structure makes it simpler to move an app between Django projects hence every application is act as an independent.

Creating Django Project:

To create a Django project we need to execute this command on the terminal or cmd prompt.

Syntax: django-admin startproject <project_name> .

Code:

“ (venv) linux@root:~/django_project/CellShop$ django-admin startproject CellShop .”

So when we install a Django. Django brings a command line uses called Django admin so this is a program that we can execute from the command line which is cmd prompt or terminal. Django-admin takes various arguments in this case we want to use argument start projects with this we were going to create a project called eShop in the current folder. This period is very important here which states that create the project in the current directory.

This will create a “CellShop” project folder with the following structure −

CellShop/

  CellShop/

      __init__.py

      settings.py

      urls.py

      wsgi.py

   manage.py

  • init.py: It means the CellShop folder is a package, so we can import various modules from this package into other modules 
  • setting.py: It is a module we define various settings for our applications 
  • urls.py: From this module, we define what should the users see when they see /index. /about, /contact, etc.
  • WSGI: It acts as a web server gateway interface.
  • manage.py: As the name implies we use this module to manage the Django project. With this we can start our web server we can work with our database, etc.

Setting Up Your Django Project:

You need to set up your project in the subfolder which is CellShop/settings.py. There are some important options which you might need to set up are: “ DEBUG = True ”.

So it will start your debugging system on. Debug mode helps you get more clear  information about your project error. Never set a DEBUG to True for a live project. However, this has to be set to True if you want the Django light webserver to serve static files. Always do it only in the development mode only.

The database can be set up through the ‘Database’ dictionary which is also located in settings.py By default the SQLite database is selected as a database Engine. Django also supports MySQL, Oracle, PostgreSQL, MongoDB, NoSQL, etc you can allocate database engine as per your requirements. SQLite is not as much secure and flexible as Mysql, oracle database, etc. 

SQLite:   “DATABASE: {‘default’:{‘ENGINE’: ‘django.db.backends.sqlite3’, …. }}”

MySQL: “DATABASE: {‘default’ {‘ENGINE’: ‘django.db.backends.postgresql_psycopg2’,  }}”

Oracle:   “DATABASE: {‘default’:{‘ENGINE’: ‘django.db.backends.oracle’, …. }}”

MongoDB:  “DATABASE: {‘default’:{‘ENGINE’: ‘django_mongodb_engine’, …. }}”

Before setting up any new database engine, make sure you have the same related database driver installed in your system.

You also have to set others options like: TIME_ZONE, INSTALLED_APPS, LANGUAGE_CODE, TEMPLATE, etc.

Now your project is successfully created and well configured make sure it is working −

To view the working status of our project we need to execute our project using this below command by typing in our terminal or cmd prompt.

Syntax: python manage.py runserver

Code: “ (venv) linux@root:~/django_project/CellShop$ python3 manage.py runserver ”

Once the above code is execute successfully. It will generate a developer server and give something like this −

(venv) linux@root:~/django_project/CellShop$ python3 manage.py run server

Watching for file changes with StatReloader

Performing system checks…

System check identified no issues (0 silenced).

You have 18 unapplied migration(s).

Run ‘python manage.py migrate’ to apply them.

April 08, 2021 – 18:01:29

Django version 3.2, using settings ‘CellShop.settings’

Starting development server at http://127.0.0.1:8000/

Quit the server with CONTROL-C.

Django – Apps Life Cycle:

This Django folder contains multiple apps. These apps don’t represent the entire applications. They are small functional areas in our Django project. For example: Imagine you have to build a website or web app like Amazon. Amazon is a big eCommerce website. It has so many different functions. Instead of implementing all these functions in a Django project, we divide this project into small functional areas that are focus on one concern. For example, we could have functional areas like product management, order management, customer management, etc these are completely different functional areas. The functions we have for managing the customers are different from the function for managing the products. By the same token if we go to an organization there are small departments or small offices specializing in different areas. So with this analogy, we divide it Django project into multiple Django apps. Each app is focus on one functional area. Each app is essentially a python package. 

A project is an addition of several applications. All application has an objective or goals and can be reused into another project, like the logiin, registration form on a website or web app can be an application and can be reused for others projects.

  1. Create an Application

Now for creating our first app open your terminal and just write the below command in your command line terminal or cmd prompt.

Syntax: python manage.py startapp <app_name>

Code: 

    “(venv) linux@root:~/django_project/CellShop$ python3 manage.py startapp products”

You have successfully created a product’s application in your Django project. Django created a “products” folder with the following application structure −

products/

    migrations/

     __init__.py

     admin.py

     apps.py

     models.py

     tests.py

     views.py

  • __init__.py – Just make sure python treats this folder as a package.
  • admin.py – This file helps you to make changes to the application on the          administrator interface.
  • Apps.py – It is used to store various configure settings for these apps and it also contains AppConfig functions.
  • models.py – This is where all system models are stored.
  • tests.py – This is where your unit test is located.
  • views.py – This is where your app views are.

To connect our new apps with our Django projects:

We currently have our “products” application, now we need to register it with our Django “CellShop” project. To do so, update the INSTALLED_APPS which is located in your project settings.py file (add your application name) –

INSTALLED_APPS = (

   ‘django.contrib.admin’,

   ‘django.contrib.auth’,

   ‘django.contrib.contenttypes’,

   ‘django.contrib.sessions’,

   ‘django.contrib.messages’,

   ‘django.contrib.staticfiles’,

   ‘products.apps.ProductsConfig’,

)

Django – Admin Interface:

One of the most powerful parts of Django is it contains default automated admin controller interface. Django administrator site reads metadata from your models to provide a quick, modular link where trusted users can manage content on your site. On the Django administrator site the use of the controller is limited to the organization’s internal management tool. It is not intended to build your entire frontend work.

The admin manager has many custom tricks, but be careful not to try to use only those hooks. If you need to provide an interface-process interface that separates the start-up details of tables and forums, it may consume a lot of time to write your own views.

Administrator is enabled on the default project template used by startproject. Admin interface is based on Django. countrib module To work you need to make sure other modules are imported into INSTALLED_APPS and MIDDLEWARE_CLASSES tuples of CellShop/ settings.py file.

For INSTALLED_APPS make sure you have –

INSTALLED_APPS = (

   ‘django.contrib.admin’,

   ‘django.contrib.auth’,

   ‘django.contrib.contenttypes’,

   ‘django.contrib.sessions’,

   ‘django.contrib.messages’,

   ‘django.contrib.staticfiles’,

   ‘products.apps.ProductsConfig’,

)

MIDDLEWARE_CLASSES –

MIDDLEWARE_CLASSES = (

   ‘django.contrib.sessions.middleware.SessionMiddleware’,

   ‘django.middleware.common.CommonMiddleware’,

   ‘django.middleware.csrf.CsrfViewMiddleware’,

   ‘django.contrib.auth.middleware.ConfirmationMiddleware’,

   ‘django.contrib.messages.middleware.MessageMiddleware’,

   ‘django.middleware.clickjacking.XFrameOptionsMiddleware’,

)

Before launching your server, to access your Admin Interface, you need to start the database

1. You need to make migrations after creating the models in products/models.py

Syntax: $ python manage.py makemigrations

Code: 

“ (venv) linux@root:~/django_project/CellShop$ python3 manage.py makemigrations”

2. You need to simple write below code to do migrations:

Syntax: $ python manage.py migrate

Code: “ (venv) linux@root:~/django_project/CellShop$ python3 manage.py migrate”

Syncdb is a django shell command to create tables for the first time for applications added to INSTALLED_APPS for settings.py. Syncdb will create the required tables or groups depending on your database type, which is required for the administrator interface to work. Even if you do not have a superuser, you will be notified that you have created it.

If you need to create a user to sign in with, use the createuperuser command. 

By default, login to administrator requires that the user has the is_staff attribute set to True.

Finally, decide which models of your application should be configured in the controller interface. For each of these types, register with the administrator as described in ModelAdmin.

If you already have a superuser or have forgotten it, you can always build using the following code –

Syntax: $ python manage.py createuperuser

Code:  

“ (venv) linux@root:~/django_project/CellShop$ python3 manage.py createuperuser”

After executing the above code on the terminal it will ask for username, email, and password. So according to your requirement complete those process and it will create a superuserDjangon) for you.

Now to start Admin Interface, we need to make sure we have prepared the URL of the administrator interface. Open CellShop / urls.py and you should have something in common 

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path(‘admin/’, admin.site.urls),

path(”, include(‘products.urls’)),

path(‘accounts/’, include(‘accounts.urls’)),

]

Now just execute our project to the webserver.

Code: $ python manage.py runserver

And your administrator interface is available at: http: // 127.0.0.1: 8000 / admin /

Once connected to your superuser account, you will see the default admin panel screen which consists of Users and Groups. 

That interface will allow you to control Django groups and users, with all the models registered in your app. The interface gives you the ability to make at least some “CRUD” functionality (Create, read, update, delete) to your models.

Django – Creating Views

View Djjango is a layer of business logic. It is responsible for processing the user request and sending back a valid response. It downloads data from the model, gives each template access to the specific data to be displayed, or can perform further data processing earlier. Nowadays, Django views can be a process of requesting and retrieving feedback, or it can be classed able to do much the same with Laravel and Rails controllers.

The view function, or “view” for short, is simply a Python function that takes a web request and returns the answer to the web. This response could be HTML content on a Web page or redirect, or a 404 error, or an XML document, or an image, etc. 

Example: When using views to create web pages, note that you need to link a views to an appropriate URL to see it as a web page.

In Django, views should be created in the views.py app file.

Simple view

We will create a simple view on the products app to say “Hello to my app!”

Write below code in your products/view.py –

from django.http import HttpResponse

def new(request):

return HttpResponse(‘Hello to my app!’)

In this view, we use HttpResponse to provide HTML (as you may have noticed that we have HTML with a strong code in view). To view this idea as a page we just need to put it in a URL (this will be discussed in the next subtopics).

We used HttpResponse to provide HTML in preview. This is not the best way to provide pages. Django supports MVT pattern to create a preview, Django – MVT likes, we will need –

Template: products / templates / hello.html

And also do some sorts of extra works in our projects i.e CellShop / settings.py there is a TEMPLATE in that go to directories (DIRS) and add a BASE_DIR and a name of our templates folders it simply joins our base directory and templates together.

Before Changes DIRS: 

TEMPLATES = [

{

‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,

‘DIRS’: [],

‘APP_DIRS’: True,

‘OPTIONS’: {

‘context_processors’: [

‘django.template.context_processors.debug’,

‘django.template.context_processors.request’,

‘django.contrib.auth.context_processors.auth’,

‘django.contrib.messages.context_processors.messages’,

],

},

},

]

After Changes DIRS:

TEMPLATES = [

{

‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,

‘DIRS’: [BASE_DIR, ‘templates’],

‘APP_DIRS’: True,

‘OPTIONS’: {

‘context_processors’: [

‘django.template.context_processors.debug’,

‘django.template.context_processors.request’,

‘django.contrib.auth.context_processors.auth’,

‘django.contrib.messages.context_processors.messages’,

],

},

},

]

Now we can write in our view like –

from django.shortcuts import render

from django.http import HttpResponse

def hello(request, id):

           return render(request, ‘hello.html’)

Views can also receive parameters –

from django.shortcuts import render

from django.http import HttpResponse

def hello(request, id):

text = “<h1> welcome to my app id % s! </h1>”% id

           return HttpResponse(text’)

Views can also return objects in form of dictionary-

from django.shortcuts import render

from django.http import HttpResponse

from .models import Product

def product(request):

products = Product.objects.all()

return render(request, ‘index.html’, {‘products’: products})

When linked to a URL, the page will display the forwarded number as a parameter. Note that the parameters will be passed by URL’s.

Django – Creating Views:

The Django URL router is much more complex than other frameworks like Laravel, etc. The problem with it is that it uses common expressions that are not easy to use for beginners. However, creating the URL path itself is not difficult at all, it is just a syntax that you may not feel comfortable with at first.

Now we have a practical idea as explained in the previous topics. We want to access that idea by URL. Django has its own way to map URL and is done by editing the urls.py project of your file (CellShop / urls.py). The URLS.py file looks like –

“””Pyshop URL Configuration

     ….

“””

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path(‘admin/’, admin.site.urls),

path(”, include(‘products.urls’)),

path(‘accounts/’, include(‘accounts.urls’)),

]

When a user makes a page request to your web app, the Django controller replaces the corresponding view with the url.py file, and retrieves the HTML response or 404 error that is requested File not found, if a file is not available. 

In urls.py, the most important thing is listings for “urlpatterns”. This is where you define the map between URLs and views. Mapping is the motto of similar URL patterns –

from django.urls import path

from . import views

urlpatterns = [

path(”, views.front, name=’front’),

path(‘product’, views.index, name=’index’),

path(‘hello/’, views.new),

]

The tagline lists the URL “hello/” to the hello view created in the myapp  products / view.py file. As you can see above the map is made up different elements are as follows-

  • Python mode of view – Same as when importing module.
  • The route dispute must be a thread or gettext_lazy() containing the URL pattern.
  • Dispute view is a view function or an as_view() class-based viewing result. It can also be written as django.urls.include().
  • Name – In order to perform URL reversal, you will need to use the URL patterns named after them as in the examples above. When you’re done, just start the server to access your view via: http: //127.0.0.1/hello
  • Normally, the location of the application name should be specified by the installed module. If the application namespace is set, the namespace dispute can be used to set a different example location.
  • include() also acceptance as a dispute can be a retrieval of URL or 2-Tuple patterns that contain probability as well as system name names.

Editing your URLs:

So far, we are creating URLs in the “CesllShop / urls.py” file, however as mentioned earlier about Django and app building, the best point was to be able to re-use programs for various projects. You can easily see what the problem is, if you save all your URLs to the “projecturl.py” file. The best thing is to create a “urls.py” for each application and install it in our main urls.py file.

We need to create a urls.py file on myapp using the following code –

from django.urls import path

from . import views

urlpatterns = [

path(”, views.front, name=’front’),

path(‘product’, views.index, name=’index’),

path(‘hello/’, views.new),

]

Thereafter CellShop / urls.py will switch to the following –

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path(‘admin/’, admin.site.urls),

path(”, include(‘products.urls’)),

path(‘accounts/’, include(‘accounts.urls’)),

]

We’ve included all URLs from the myapp app. Home.html achieved with “/ hello” is now “/ myapp / hello” which is the best and most understandable web application.

Now let’s assume we have another idea for myapp “morning” and we want to put it in myapp / urls.py, then we will change our myapp / urls.py into –

from django.urls import path

from . import views

urlpatterns = [

path(”, views.front, name=’front’),

path(‘product’, views.index, name=’index’),

path(‘hello/’, views.new),

path(‘morning/’, views.new, name=”morning”),

]

As you can see, we are now using the first item of our urlpatterns Tuple. This can be useful if you want to change the name of your application.

Sending Parameters to Views

Now that we know how to map URL, how to edit them, now let’s see about errors handlers.

django.conf.urls jobs for use at URLconfs

static () 

static.static (start, view = django.views.static.serve, ** kwargs) 

Assistant task to retrieve the URL pattern for moving files in debug mode:

from django.conf import settings

from django.conf.urls.static import static

urlpatterns = [

    # … all your URLconf goes here …

] + static (settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

url ()

This function is alias in django.urls.re_path ().

Error Handler:

1. 400:

A drive, or cable representing a full Python input line in view that should be called when an HTTP client has sent a request that created an error and a response with 400 status code.

By default, this is Django.views.defaults.bad_request (). If you are using a custom view, make sure it accepts different requests and arguments and returns HttpResponseBadRequest.

2. 403:

An expensive string, or a string representing a full Python import line in the view to be called if the user does not have the necessary permissions to access the app.

By default, this is Django.views.defaults.permission_denied (). If you are using a custom view, make sure it accepts the application with different arguments and returns HttpResponseForbidden.

3. 404:

A dial, or a string representing a full Python import line in the view that should be called if there are no matching URL patterns.

By default, this is Django.views.defaults.page_not_found (). If you are using a custom view, and if it got errors that it will returns HttpResponseNotFound.

4. 500:

A drive, or cable representing a full Python input line in the view should be called in case of server errors. Server errors occur when you have time-lapse errors in the view code.

By default, this is Django.views.defaults.server_error (). If you are using a custom view, make sure it accepts the request dispute and retrieves HttpResponseServerError.

Django – Creating Template System

A template layer is used to separate data from the way it is presented and viewed by the user. The template layer is the same as the MVC view layer. There are already template formats besides HTML, if you want to generate XML documents or JSON files, etc.

DRY is one of the main building codes of Django and is a design pattern that stands for Do Not Repeat Yourself. This is exactly what it means, it means that you should not, at least in most cases, copy and paste the code. Instead, your template, for example, should be divided into useful items such as a sidebar, main navigation bar, page title, page footer and so on. This reduces duplication and is designed to write code that is efficient and neat.

One of the things that Django does is different is how serious he is about safety. This really affects the writing of the template.

Simply put, Django prohibits coding in the template layer and provides access only to the display of logic, which is a simple but effective solution to many web crashes.

Django makes it possible to distinguish between python and HTML, python goes to view and HTML enters templates. Linking the two, Django relies on dedicated performance and the language of the Django template.

Django Template (DTL) Language:

Django template engine provides small language to define the user-facing layer of the program.

Flexible Display:

The variation looks like this: {{variable}}. The template replaces the dynamic variable sent by the view to the third parameter of the rendering function. Let’s change our hello.html to show today –

hello.html

<html>

   <body>

      Hello World !!! <p> Today is {{today}} </p>

   </body>

</html>

After that our view will change to –

def hello (request):

   today = datetime.datetime.now(). date ()

   roll back (request, “hello.html”, {“today”: today})

We will now get the next result after getting the URL / myapp / hello –

Hello World!!!

Today is September 11, 2015

As you may have noticed, if the variable is not a thread, Django will use the __str__ method to indicate it; and with the same goal, you can achieve the quality of an object just as you do in Python. 

For example: if we wanted to show the date year, my variable would be: {{today.year}}.

Filters:

They help you adjust the dynamics during the display. The filter structure looks like the following: {{var | filters}}.

Other examples –

    {{string | truncatewords: 80}} – This filter will shorten the thread, so you’ll only see the first 80 words.

    {{string | lower}} – Converts a unit of characters into lowercase letters.

    {{string | escape | linebreaks}} – The content of the line runs, then converts the line split into tags.

Tags:

Tags allow you to perform the following tasks: if conditions, loop, template asset and many more.

As like Python you can use if, else and elif in your template –

<html>

   <body>

      Hello World !!! <p> Today is {{now}} </p>

      Singa

      {% if now.day == 1%}

      the first day of the month.

      {% elif now.day == 30%}

      last day of the month.

      {% more %}

      I do not know.

      {% endf %}   

   </body>

</html>

In this new template, depending on the date, the template will give you a certain value.

Mark the tag for

Like ‘if’, we have the ‘for’ tag, which works in the same way as Python. Let’s change our mindset so we can move the list to our template –

def hello (request):

   now = datetime.datetime.now (). date ()

week_days = [‘Sun’,’Mon’, ‘Tue’, ‘Wed’, ‘Thu’, ‘Fri’, ‘Sat’]

   return (request, “hello.html”, {“now”: now, “days_of_week”: week_days})

Block and Expand Tags:

The template program cannot be completed without a template asset. Which means that when designing your own templates, you should have a large template with holes for a child template to fill in according to their need, such as a page that may require a special css of the selected tab.

Syntax: {% block <block_name>%}{% endblock %}

Code: 

”””

{% extends ‘base.html’ %} {% block content %}

<div

class=”bg-image d-flex justify-content-center align-items-center”

style=”

background-image: url(‘https://www.hdwallpapersfreedownload.com/uploads/large/fruits/fruits-background.jpg’);

height: 100vh;

>

<h1 class=”text-white”>Fresh Fruits Shop</h1>

</div>

{% endblock %}

”””

Django – Models:

Django model uses a powerful ORM layer that makes it easy to deal with databases and data and speeds up the development process.

With the exception of Object-Relational-Mapping, developers will need to create their own tables and define queries or procedures that sometimes translate into large SQL values that tend to be complex and difficult to track.

The ORM layer allows you to write all table descriptions with a simple python code, and takes care of translating that into the appropriate query language of choice, and also helps with CRUD functionality.

In fact, the developer does not need to know the most complex SQL or what it translates, however, it is important to note that understanding SQL will allow you to write better and faster questions and make your website more secure.

Unlike other frameworks, the models are placed in a single file, usually, models.py, which can make it sound cramped for large projects.

Django supports multiple data systems. SQLite is ready for testing and development as it can be used out of the box without installing any other software. For production, you can go to MYSQL or PostgreSQL, and if you want a NoSQL database, you can use MongoDB in our Django projects.

Code:

from django.db import models

class Product(models.Model):

name = models.CharField(max_length=255)

price = models.FloatField()

stock = models.IntegerField()

image_url = models.CharField(max_length=2083)

class Offer(models.Model):

code = models.CharField(max_length=10)

description = models.CharField(max_length=255)

discount = models.FloatField()

If you wish to learn more such concepts, join the pool of free online courses offered by Great Learning Academy and upskill today!

0

LEAVE A REPLY

Please enter your comment!
Please enter your name here

10 + fifteen =