DJango Introduction
As per the documentation, Django is a high-level web development framework for python which helps in rapid development and clean, programatic design of web application. With django, you can take web application to launch within hours.
Features of django
- Free and Open source
- Rapid web development — help developers take applications from concept to completion as quickly as possible.
- Fully loaded - takes care of user authentication, content administration, site maps, RSS feeds, and many more tasks — right out of the box.
- Secure — helps developers avoid many common security mistakes, such as SQL injection, cross-site scripting, cross-site request forgery and clickjacking. Its user authentication system provides a secure way to manage user accounts and passwords.
- Object Relational Mapping (ORM) — Provide interface to connect and execute queries on databases
- Other features — Versatile, URL Routing, HTML Templating, Scalable, Form Handling
Django Architecture
Django uses Model-View Controller (MVC) architecture. However, there are different terminologies for these. The components of django architecture are:
- URL Patterns — defines url routing of the apps
- Views — defines logic and control flow of the app and HTTP responses that are returned
- Models — provide data layer to construct db schema and execute queries
- Templates — define the template for HTML files
How does django works?
- When django application receives web request, it looks at URL patterns to decide which view function to use and route request to respective view function
- Upon receiving the request, Views function first make database calls using Models and then pass the data from DB and HTTP request to respective template html file.
- Template takes data and HTTP request from views and render the html response.
URL Patterns
URL patterns are the first part of application code where requests are received and those requests are passed to the respective View function.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path('home/', View.home, name='home') #To accept parameters from URL
path('userdetails/<int:user_id>/' , View.userdetails)
]
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 incomingHttpRequest
object has aurlconf
attribute (set by middleware), its value will be used in place of theROOT_URLCONF
setting. - Django loads that Python module and looks for the variable
urlpatterns
. This should be a sequence ofdjango.urls.path()
and/ordjango.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 todjango.urls.path()
ordjango.urls.re_path()
.
More info on URLs: https://docs.djangoproject.com/en/3.1/topics/http/urls/
Views
A View is a Python function which takes HTTP request as an argument and return HTTP response. This response could be HTML content or data from Database or XML Content or a file or an image etc…
Example:
def hero_list(request):
if request.method == 'GET':
queryset = Hero.objects.all()
serializer = HeroSerializer()
return Response(serializer.data)
if request.method == 'POST':
serializer = HeroSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)"""
More about views: https://docs.djangoproject.com/en/3.1/topics/http/views/
Django Models
Models creates the data layer for the django app, this means they define structure of data and how we store them in database. Models also leverage the django’s ORM to query data from database. Model is class that inhert from django.db.models.Model and defines fields as its attributes.
In simple understanding, we can conceptualise of models as a spreadsheet. Each model is a table in spreadsheet and each field in a model represent the column of the spreadsheet table. Each record (our data) in the database will be each row of the spreadsheet table.
Example:
Let’s define a Patient model where we need to store name, age, vaccine, doctor and date.
from django.db import modelsClass Patient(models.Model):
GENDER = [('M', 'Male'), ('F', 'Female'))]
name = models.CharField(max_length=100)
age = models.IntegerField(max_length=100)
doctor = models.CharField(max_length=100)
vaccine = models.CharField(max_length=100)
date = models.DateTimeField()
address = models.TextField(blank=True)
gender = models.CharField(max_length=1, choices=GENDER, blank=True)
Field Types: CharField, IntegerField, DateTimeField, EmailField, URLField, DecimalField, BooleanField.
Relation Data Field types: ForeignKey (relate data between to models), ManyToManyField (relate a record to many records of a model).
More info: https://docs.djangoproject.com/en/3.1/ref/models/fields/
Django Migrations
As we just learnt, Models define the structure of database, Migrations are responsible for generating or creating necessary scripts to change this structure through time as we update our code to change our models.
The migrations which are created at the beginning of the app creation are called initial migrations.
The migrations which are created but not yet run are called unapplied migrations.
When migration is needed ?
- When new model is added
- When field of a model is added/updated
- Any other changes to model
To create migrations
python manage.py makemigrations
To run migrations
python manage.py migrate
Templates
Templates files are HTML files with extra syntax. Django provides convenient way to generate HTML content dynamically using templates.
Example:
<div>
{% for pet in pets %}
<div class="petname">
<a href="{% url 'pet_detail' pet.id %}">
<h3>{{ pet.name|capfirst }}</h3>
</a>
<p>{{ pet.species }}</p>
{% if pet.breed %}
<p>Breed: {{ pet.breed }}</p>
{% endif %}
<p class="hidden">{{ pet.description }}</p>
</div>
{% endfor %}
</div>
Syntax:
- To define variable — {{ variable_name }}. Ex: pet_name in above example (Line no. 5)
- To define tags(used in loops) — {% tag_name %} . Ex: pets in above example (Line no. 2)
- To use filters with variables — {{ variable_name | filter }}. Ex: “pet_name | capfirst” in above example (Line no. 5)