0% found this document useful (0 votes)
13 views16 pages

Django guide

Django is a free and open-source web framework for building applications with Python, utilizing a Model-Template-View (MTV) design pattern. The document outlines the basic structure of a Django project, including essential files and components, as well as how to set up a database connection, perform CRUD operations, and create a RESTful API. It also covers the use of Django's admin interface and the integration of third-party libraries for working with non-relational databases like MongoDB.

Uploaded by

Night-Z Kun
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)
13 views16 pages

Django guide

Django is a free and open-source web framework for building applications with Python, utilizing a Model-Template-View (MTV) design pattern. The document outlines the basic structure of a Django project, including essential files and components, as well as how to set up a database connection, perform CRUD operations, and create a RESTful API. It also covers the use of Django's admin interface and the integration of third-party libraries for working with non-relational databases like MongoDB.

Uploaded by

Night-Z Kun
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/ 16

Django

What is Django
Django is a free and open-source framework for building web applications with
python.

How does the web work


Frontend
The part that the user sees and interacts with.

Backend
The part that runs on a web-server.

URL
Uniform Resource Locator, a way to locate any resource on the internet.

HTTP
Hypertext Transfer Protocol, defines how client and server communicate.

API
Application Programming Interface, a set of rules and tools that allows
different software applications to communicate and interact with each other,
enabling easy integration of functionalities without the need to understand the
internal workings of the systems involved.

Django project initialization

💡 “pipenv install django” ⇒ “pipenv shell” ⇒ select interpreter ⇒ “django-


admin startproject project name .” ⇒ “python manage.py runserver”

Django 1
Project initial files
manage.py
command-line utility that u can use to interact with django in various
ways.

settings.py
contains settings for the django project like database, middleware, static,
template…etc.

urls.py
Project-level URLs, located in the main project directory, used to include
the URLs of all the apps that make up the project.

wsgi/asgi
used to deploy the django project to an asgi or wsgi server.

__init__.py
a mark for python to indicate that the directory should be considered a
python package.

App initial files


admin.py
How the admin interface for the app is gonna look like.

apps.py
Where we configure the app (could be called config)

models.py
Where we define the model classes for the app.

Field types
https://docs.djangoproject.com/en/5.0/ref/models/fields/#field-types

Choices
https://docs.djangoproject.com/en/5.0/ref/models/fields/#choices

One-To-One

Django 2
One-To-Many

Many-To-Many
tests.py
Where we write our unit tests

views.py
Where we define our view functions, request handlers.

urls.py
App-level URLs, located in each app’s directory, used to define the URL
Pattens of each app (home, about, contact…)
Common App folders
Templates
Where we put all of our template files.

static
where we put our static assets like CSS, JS, images…

Django MTV
MTV stands for Model-Template-View, and it is a design pattern used by the
Django web framework for organizing code and structuring web applications.

Model
The model represents the data and business logic of the application. It defines
the structure of the data and provides an interface to interact with the
database.

Template
The template represents the presentation layer and defines how the data
should be displayed.

View
The view handles the processing of data, interacts with the model, and returns
an appropriate response. It receives user input, processes it, and
communicates with the model and template.

Django 3
How it works
Request Handling
When a user makes a request, it is first handled by a Django URL mapper,
which identifies the appropriate view function to handle the request based
on the URL patterns.

View Processing
The identified view function processes the request, interacts with the
model if needed, and decides how to respond. The view typically returns
an HTTP response.

Template Rendering
If the response involves rendering HTML, the template engine is used to fill
in the dynamic content in the HTML templates with data from the view.

Response Sent
The final response, whether it's HTML content, JSON data, or other types,
is sent back to the user's browser.

Models
Creating models
from django.db import models

class ClassName (models.Model):


#we use choice fields when we're dealing with things tha
#are limited to some options that we know of.
PROP2_CHOICE1 = 'DBName'
PROP2_CHOICE2 = 'Expl'
PROP2_CHOICES = [
(PROP2_CHOICE1, 'Human_readable_name'),
(PROP2_CHOICE2, 'Example'),
...,
]
#a normal prop

Django 4
prop1 = models.FieldType(props)
#a choice prop
prop2 = models.FieldType(props, choices = PROP2_CHOICES
#OneToOne relationship (we specify the parent in the chi
#the parent one because django automatically creates the
prop3 = models.OneToOneField(parent,on_delete = models.{C
#OneToMany relationship (we put the FK in the class that
prop3 = models.ForeignKey(parent,on_delete = models.{CASC
#ManyToMany relationship(prop with plural name)
prop4s = models.ManyToManyField(class2, related_name = '

Some links
Django Field Types

https://docs.djangoproject.com/en/5.0/ref/models/fields/#field-types

Choices
https://docs.djangoproject.com/en/5.0/ref/models/fields/#choices

Setting up the database


Migrations
In django, we make migrations to update the database based on the models
that we have in the code.

python manage.py makemigrations

pythong manage.py migrate

Customizing DB Schemas

#here we're customizing the indexing of our model.


class ClassName (models.Model):
class Meta:
Indexes = [

Django 5
models.Index = (fields = ['First_Name', 'Last_Nam
]

Django Meta Options


https://docs.djangoproject.com/en/5.0/ref/models/options/#
Connecting to database
Pymongo is a very useful library here.

(later in the ODM section)

Django ORM(Object-Relational Mappers)


Django ORM
when we want to deal with data from the database, normally we write an SQL
code, execute it and store it through an object that we create. Here comes
ORM’s utility, it maps objects to relational records and frees us from additional
code and complexity. (works only with relational databases).

⚠️ We won’t use ORM because it works with relational Databases and


we’ll use ODM or some third party libraries instead because we’re
working with MongoDB, a non-relational database.

Django ODM(Object Document Mapper) &


Third-Party Libraries
Useful libraries
Djongo, Mongoengine, PyMongo , Motor, Marshmallow-mongodb

Djongo official guide


https://www.djongomapper.com/integrating-django-with-mongodb/

PyMongo Official Guide


https://pymongo.readthedocs.io/en/stable/tutorial.html

Pymongo Tutorial

Django 6
https://www.youtube.com/watch?v=UpsZDGutpZc&list=PLzMcBGfZo4-nX-
NCYorkatzBxjqRlPkKB&pp=iAQB
How to use Pymongo with Django
Installation

pip install pymongo

Connection Setup

import pymongo
from pymongo import MongoClient

Connection to database (mongodb atlas in this case)

#we write this in a db_conn.py under project directory


connection_string = "mongodb://<username>:<password>@<hos
client = MongoClient(connection_string)
db = client["your_database_name"]

Working with collections of the DB


Using the DB object that represents our database, we can access
collections of it.

#we write this in models.py


from db_conn import db
collection = db["collection_name"]

CRUD

We gonna work on the CRUD operations in views.py

from .models import collection

Create

Django 7
def create_func():
first_names = ["name1", "name2", "name3"]
last_names = ["ln1", "ln2", "ln3"]
ages = [21, 22, 23]

for first_name, last_name, age in zip(first_names,


doc = {"first_name": first_name, "last_name":
example_colllection.insert_one(doc)

create_func()

def insert_func():
collection = db.collectionname
test_document = {
"name" : "Tim",
"age" : 21
}
collection.insert_one(test_document)

insert_func()

Read

import pprint
printer = pprint.PrettyPrinter()
def find_all_people_func():
people = person_collection.find()
for person in people:
printer.pprint(person)

find_all_people_func()

def find_tim_func():
tim = person_collection.find_one({"first_name": "T

Django 8
printer.pprint(tim)
find_tim_func()

def count_people_func():
count = person_collection.count_documents(filter=
#alternative
count = person_collection.find().count()
print("the number of people is", count)

count_people_func()

from bson.objectid import ObjectId


def get_person_by_id_func(person_id):
_id = ObjectId(person_id)
person = person_collection.find_one({"_id": _id})
printer.pprint(person)

get_person_by_id_func("idexample189156198746")

def get_age_range_func(min_age, max_age):


query =
{
"$and":
[
{"age": {"$gte": min_age}},
{"age": {"$lte": max_age}}
]
}
people = person_collection.find(query).sort("age")
for person in people:
printer.pprint(person)

get_age_range_func(18, 30)

Django 9
#defining the columns that we want to get
def columns_func():
columns = {"_id": 0, "first_name": 1, "last_name":
people = person_collection.find({}, columns)
for person in people:
printer.pprint(person)

Update

from bson.objectid import ObjectId


def update_person_by_id_func(person_id):
_id = ObjectId(person_id)
all_updates = {
"&set":{"new_field": True},
"&inc":{"age": 1},
"&rename":{"first_name":"first","last_name":"l
}
person_collection.update_one({"_id": _id}, all_upd

update_person_by_id_func("1653128653412")

from bson.objectid import ObjectId


def replace_person_by_id_func(person_id):
_id = ObjectId(person_id)
new_doc = {
"&set":{"new_field": True},
"&inc":{"age": 1},
"&rename":{"first_name":"first","last_name":"l
}
person_collection.replace_one({"_id": _id}, new_on

replace_person_by_id_func("1653128653412")

Delete

Django 10
from bson.objectid import ObjectId
def delete_doc_by_id_func(_id):
_id = ObjectId(person_id)
person_collection.delete_one({"_id":_id})

delete_doc_by_id_func("1653128653412")

Mongodb Operators
https://www.w3schools.com/mongodb/mongodb_query_operators.php

Django Admin

💡 The django admin allows us to make a user-friendly interface to


manage our application’s data.

Creating an admin user


python manage.py createsuperuser

Customizing the admin interface


Through urls.py we can customize our admin interface.

Admin site attribute

https://docs.djangoproject.com/en/5.0/ref/contrib/admin/#adminsite-
attributes

Registering admin models


in the app’s admin.py file we import our models and register the admin to
them.

from . import models


admin.site.register(modelName)

Customizing the models appearances

Django 11
Through the models.py file, we can change the order and appearance of our
models in the admin site.

#example, we want to make the collection title as the title


#we add the following code under the model class code
def __str__(self) -> str:
return self.title

Django Instance Methods


https://docs.djangoproject.com/en/5.0/ref/models/instances/#other-
model-instance-methods

We can also change the order by changing the meta code

class Meta:
ordering = ['title']

Django Meta Options


https://docs.djangoproject.com/en/5.0/ref/models/options/#
Customizing the list page
We can customize the list that appears on the admin page through the
admin.py file.

@admin.register(models.Product)
class ProductAdmin(admin.ModelAdmin):
#to make the unit price appear with the title
list_display = ['Title','unit_price']
#to make the unit price directly editable through the list
list_editable= ['unit_price']
#to make the list show only 10 products per page
list_per_page = 10

ModelAdmin Options
https://docs.djangoproject.com/en/5.0/ref/contrib/admin/#modeladmin-
options

Django 12
The rest of the admin part is not needed for now.
Django RESTful API
Django RESTful API
Resources
Resources are basically objects in our app that clients will access through a
URL.

ResourceRepresentations
Resource Representations are formats in which we represent our resources
that are suitable for working with APIs.
Like : XML, HTML, Json…etc.

HTTP Methods
GET

💡 Used for getting a resource or a collection of resources

We pass a GET request simply through accessing the URL of a collection


of resources or a single resource by adding it “/id”

POST

💡 Used for Creating a resource

We pass a POST request to the URL “.../example” by inserting the data that
we’re creating in a JSON object in the body of the request.

PUT

💡 Used for updating all the props of a resource

Django 13
We pass a PUT request to the URL “…/example/id” by including a JSON
object in the body of the request.
PATCH

💡 Used for updating a part of a resource

We pass a PATCH request to the URL “…/example/id” by including a JSON


object in the body of the request.

DELETE

💡 Used to delete a resource.

We pass a DELETE request to the URL “…/example/id” without including


any other details because all we need to just delete a resource is its id.
Installing Django REST Framework
pipenv install djangorestframework

Then we add it to the list of our installed apps in settings.py.

'rest_framework',

Creating API Views

💡 We gonna replace Django’s HTTP Request and HTTP Response by


REST Framework’s Request and response because it’s much better
and more powerful.

The Django REST Framework also provides us with a very useful


interface to test our API endpoints.

Steps

Django 14
1• We include the App URLs in the Global URLs.py file

2• We customize the app’s URLs.py

3• We create our view functions

from rest_framework.decorations import api_view


from rest_framework.response import Response
@api_view()
def product_list(request):
return Response()

Serializers
Serializing Data
Transforming our data from object to python dictionary so that we can
pass it to JSONRenderer method and we get our data in a JSON format
useable for APIs.

Deserializing Data
The opposite of Serializing Data.

Serializers

💡 We use serializers to convert our model instances to dictionaries,


they are also useful for data validation and other purposes like
choosing which data to show or hide from the model.

It bridges the gap between Internal and External representations


of our Models.

We write the code of our serializers in serializers.py file


In serializers, we define our fields in the same way we do in models.

#Model
class Product(models.Model):

Django 15
title = models.CharField(max_length=255)

#Serializer
class ProductSerializer(serializers.Merializer):
title = serializers.CharField(max_length=255)

Guide

https://www.django-rest-framework.org/api-guide/serializers/

#So our view function becomes this way


@api_view()
def product_detail(Request, id):
Product = Product.objects.get(pk=1)
serializer = ProductSerializer(product)
return Response(serializer.data)
#django will automatically represent our dictionary in JSO

Django 16

You might also like