Django guide
Django guide
What is Django
Django is a free and open-source framework for building web applications with
python.
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 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.
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
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
Customizing DB Schemas
Django 5
models.Index = (fields = ['First_Name', 'Last_Nam
]
Pymongo Tutorial
Django 6
https://www.youtube.com/watch?v=UpsZDGutpZc&list=PLzMcBGfZo4-nX-
NCYorkatzBxjqRlPkKB&pp=iAQB
How to use Pymongo with Django
Installation
Connection Setup
import pymongo
from pymongo import MongoClient
CRUD
Create
Django 7
def create_func():
first_names = ["name1", "name2", "name3"]
last_names = ["ln1", "ln2", "ln3"]
ages = [21, 22, 23]
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()
get_person_by_id_func("idexample189156198746")
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
update_person_by_id_func("1653128653412")
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
https://docs.djangoproject.com/en/5.0/ref/contrib/admin/#adminsite-
attributes
Django 11
Through the models.py file, we can change the order and appearance of our
models in the admin site.
class Meta:
ordering = ['title']
@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
POST
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
Django 13
We pass a PUT request to the URL “…/example/id” by including a JSON
object in the body of the request.
PATCH
DELETE
'rest_framework',
Steps
Django 14
1• We include the App URLs in the Global URLs.py file
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
#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/
Django 16