Django tutorial
w3school django tutorial based on django version 5.1.7
Instaliation
create env first I did it with conda.
$ python -m pip install Django
Create Project
$ django-admin startproject mysite
Create App
An app is a web application that has a specific meaning in your project, like a home page, a contact form, or a members database.
python manage.py startapp members
Create app inside subfolder
- create app folder inside
sub folder(or just move it)
$ mkdir apps/myapp
$ python manage.py startapp myapp apps/myapp
- inside
app folderthere isapps.py. edit thenamevalue to{subfolder}.{appname} - inside
settings.pyeditINSTALLED_APPSinto{subfolder}.{appname} - inside
urls.pyediturlpatternsinto{subfolder}.{appname}.urls
Views
Django views are Python functions that take http requests and return http response, like HTML documents.
from django.shortcuts import render
from django.http import HttpResponse
def members(request):
return HttpResponse("Hello world!")
Urls
- Create a
urls.pyinside theapp folder
from django.urls import path
from . import views
urlpatterns = [
path('members/', views.members, name='members'),
]
Now this is specific for the members app.
We have to do some routing in the root dir(project dir) as well.
- add the app inside the
root dirurls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('members.urls')),
path('admin/', admin.site.urls),
]
Templates
-
Create a
templatesfolder inside themembersfolder, and create a HTML file namedmyfirst.htmland put any simple html -
Modify the View
from django.http import HttpResponse
from django.template import loader
def members(request):
template = loader.get_template('myfirst.html')
return HttpResponse(template.render())
Change Settings
we need to tell Django that a new app is created.
from settings.py look for INSTALLED_APPS[] list and add the members app.
Models
In Django, data is created in objects, called Models, and is actually tables in a database.
- Inside
models.pyfile in the/members/folder. add aMembertable by creating aMember class, and describe the table fields in it
from django.db import models
class Member(modles.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
- run a command to create table in DB
python manage.py makemigrations members
Django creates a file describing the changes and stores the file in the /migrations/ folder.
The table is not created yet, you will have to run a command.
Then Django will create and execute an SQL statement, based on the content of the new file in the /migrations/ folder.
python manage.py migrate
- To review the sql you can run this.
python manage.py sqlmigrate members 0001