0% found this document useful (0 votes)
10 views

django

The document provides an overview of Django, a comprehensive web framework that includes features like an admin interface, ORM, and authentication. It outlines the setup process, creating projects, handling views and URLs, and working with models and migrations. Additionally, it covers Django's templating system, dynamic content rendering, and the use of Django REST framework for building APIs.

Uploaded by

msakhil2002
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)
10 views

django

The document provides an overview of Django, a comprehensive web framework that includes features like an admin interface, ORM, and authentication. It outlines the setup process, creating projects, handling views and URLs, and working with models and migrations. Additionally, it covers Django's templating system, dynamic content rendering, and the use of Django REST framework for building APIs.

Uploaded by

msakhil2002
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/ 11

Django

Tags

Fundamentals
A batteries included framework: it comes with a lot of features.

Admin interface

Object-relational Mapper

Authentication package

Data for Caching data

we can give API end points on the server to get the data

Setup
install python from browser

First project
pipenv install django

the command django-admin lists out all possible comands

djangoadmin startproject creates a project

Dynamic web content:


suggested reading : introduction to networking

Django 1
the browser makes a socket connection to the server and then requests
something from the server. The server sends out information ( htmsl / json or
anything else) what the browser recieve is usually what ends up as a display
page.

Network sockets
http: invented n the 1990
Request for Comments
the client makes the first move.

sockets are like phone calls

Building a small browser in python

Creating new Django project:

django-admin startproject my_tennis_club

python -m Django gives the list of commands

views are used to customize what we see on the webpage .

we send out html tags to the browser and the browser renders this html.

http response is a class that helps us turn text into html

handling URL routes

Django 2
the views file can contain all views we define

from django.http import HttpResponse

HTML_STRING ="""
<h1>Hello world</h1>
"""

def home_view(request):
return HttpResponse(HTML_STRING)

in the urls.py define new url paths

from . import views


urlpatterns = [
path('',views.home_view),
path('admin/', admin.site.urls),
]

Customising the view


create a views.py file in the project folder

Django has http response


from django.http import HttpResponse

Adding Data to views


we can add data with variables in the html string

Django 3
💡 startapp:
creating a piece of the current django project

Models:

Reference

creting database models

# Create your models here.


class Article (models.Model):
Title = models.TextField()
content = models.TextField()

all models in django will inherit from models.Models

when we create and edit models, we should let django know about these actions.
Migrations are run to do that

Migrations

python manage.py makemigrations


python manage.py migrate

Writing and reading data

trying out the logic with the cli

Django 4
Doing it with code:

article_obj=Article.objects.get(id=2)
HTML_STRING =f"""
<h1>{article_obj.Title}</h1>
<p> {article_obj.content}</p>
"""

def home_view(request):
return HttpResponse(HTML_STRING)

Django templates
templates can be added as html files.

template configuration in the settings.py, add the directory to the ‘DIRS’

the html file can be rendered to a string with django’s inbuild feature.

Django 5
from django.template.loader import render_to_string

Inheritance template:
templates can inherit from other templates .

below is a base html file

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Title from base</h1>
{% block content %}
<h3>placebolder</h3>
{% endblock content %}

</body>
</html>

the block content is what gets replaced by the templates that inherit from this
base template
The child inheriting would look like this:

{% extends "base.html" %} //for inheritance

Django 6
{% block content %}
<h1>{{ title }} </h1>
<p> {{ content }}</p>
{% endblock content %}

Taking elements from database


we can take out the data (objects) from out database and render it to the views

article_queryset= Article.objects.all()

the above code takes out all the objects of Article and gives us the list.

to render this we can pass the object as an element in the context and call it in the
view

{% for x in object_list %}

<li>
<a href="articles/{{x.id}}">{{x.Title}} </a></li>

{% endfor %}

for loops and any other logical statements can be performed within the template

note that the loops are ended

if will also be ended by an endif.

Django 7
Dynamic Routing

Context processors

Deplaying Apps:

Django rest framework

Serializers :
In DRF, serializers convert Django model instances into JSON format and vice
versa.

views while using apiView

from rest_framework.views import APIView


from rest_framework.response import Response
from rest_framework import status
from core.models import Solution, Question, Grade, Subject, Chapter, Category,B

Django 8
from django.shortcuts import get_object_or_404
from .serializers import SolutionSerializer, QuestionSerializer, GradeSerializer, Su

# Generic CRUD View


class CRUDView(APIView):
model = None
serializer_class = None

def get(self, request):


"""Retrieve all instances"""
instances = self.model.objects.all()
serializer = self.serializer_class(instances, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)

def post(self, request):


"""Create a new instance"""
serializer = self.serializer_class(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)

class CRUDDetailView(APIView):
model = None
serializer_class = None

def get(self, request, pk):


"""Retrieve a specific instance"""
instance = get_object_or_404(self.model, pk=pk)
serializer = self.serializer_class(instance)
return Response(serializer.data, status=status.HTTP_200_OK)

def put(self, request, pk):


"""Update an instance"""
instance = get_object_or_404(self.model, pk=pk)

Django 9
serializer = self.serializer_class(instance, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def delete(self, request, pk):


"""Delete an instance"""
instance = get_object_or_404(self.model, pk=pk)
instance.delete()
return Response({"message": "Deleted successfully"}, status=status.HTTP_

# Creating views for each model by inheriting CRUDView and CRUDDetailView


class SolutionListCreateView(CRUDView):
model = Solution
serializer_class = SolutionSerializer

class SolutionDetailView(CRUDDetailView):
model = Solution
serializer_class = SolutionSerializer

class QuestionListCreateView(CRUDView):
model = Question
serializer_class = QuestionSerializer

class QuestionDetailView(CRUDDetailView):
model = Question
serializer_class = QuestionSerializer

class GradeListCreateView(CRUDView):
model = Grade
serializer_class = GradeSerializer

class GradeDetailView(CRUDDetailView):
model = Grade
serializer_class = GradeSerializer

Django 10
class SubjectListCreateView(CRUDView):
model = Subject
serializer_class = SubjectSerializer

class SubjectDetailView(CRUDDetailView):
model = Subject
serializer_class = SubjectSerializer

class ChapterListCreateView(CRUDView):
model = Chapter
serializer_class = ChapterSerializer

class ChapterDetailView(CRUDDetailView):
model = Chapter
serializer_class = ChapterSerializer

class BoardListCreateView(CRUDView):
model=Board
serializer_class = BoardSerializer

class BoardDetailView(CRUDDetailView):
model = Board
serializer_class = BoardSerializer

Django 11

You might also like