Django's Built-in Libraries and Functions

In this article will explain about Django web frameworks built-in libraries and functions like ORM, Authentication, Template system, admin interface, etc.

ORM-Object-Relational Mapping

Django web framework having in-built administrator database in SQLite Object-Relational Mapping. We can create models for our application database with django web framework admin database. Django Migration commands are below.

python manage.py makemigrations

python manage.py migrate	

Example Model Class

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)

Django Authentication

This library provides all user management related user authentication, password management, permissions, login and logout. Example code is given below.

from django.contrib.auth import authenticate, login

def my_view(request):
    user = authenticate(username='username', password='password')
    if user is not None:
        login(request, user)
        return HttpResponse('Logged in')
    else:
        return HttpResponse('Invalid credentials')

Template system

Django Template library is used for defining the layout of UI HTML and structure of the application. Client side UI everything will come into template system.

<!-- product_list.html -->
{% for product in products %}
    <li>{{ product.name }} - ${{ product.price }}</li>
{% endfor %}

Admin Interface

Admin user interface is an inbuilt powerful feature of Django framework. By below mentioned command, we can create a user for admin database. By creating a super user to our application, easily database can be accessed by the developer.


python manage.py createsuperuser

 admin.py


from django.contrib import admin
from .models import Product

admin.site.register(Product)

Will see some in-built functions of Django which is connected view functions to client html page. Example render, redirect and Httprespone.

render()

Render function use for returning HttpResponse Objects, JSON data and context dictionaries.

from django.shortcuts import render

def my_view(request):
    context = {'key': 'value'}
    return render(request, 'my_template.html', context)

redirect()

To redirecting web page to different url templates redirect function will be used.

from django.shortcuts import redirect

def my_view(request):
    return redirect('some-view-name')

Httprespone()

HttpResponse function will redirect to client view page. It's also used for redirecting to html template pages.

from django.http import HttpResponse

def index(request):
    return HttpResponse('HttpResponse')

Up Next
    Ebook Download
    View all
    Learn
    View all