All my findings of Django will be updated here.
Setup
Python3
Make sure you have python3 install on your computer.
Visual Studio Code (Code Editor)
Make sure you have a code editor and preferrable to have visual studio code.
Environment
Create a new folder and open it using visual studio code.
Now we need to write in the terminal
python -m pip install --upgrade virtualenv
After that, we need to create an environment using the command below
python3 -m virtualenv env
Now we have a new directory name env
now we need to activate the environment first using the command below.
cd env
cd Scripts
activate
Now we can see that we are in an environment like this (env)
Django
Now we need to install Django
pip3 install Django
If you want to check what library do we have just do
pip3 freeze
Since we have Django installed. We already fulfilled all of the requirements to start our first Django Project!
First Project with Django
First, let’s create our first project and we call it HelloWorld.
python -m django startproject helloword
As we can see once we run the command above, it creates one directory name helloworld
To start the webserver go to the same directory of manage.py
and run the command below
python manage.py runserver
Now we can see that our web server is hosted at http://127.0.0.1:8000/
. Now we can open it on the browser!
Now we want to create a new application name firstpage
and we can run the command below
python manage.py startapp firstpage
This will create one new directory name firstpage.
Every time we make new applications don’t forget to update it inside settings.py
Let's output hello world
on the page. To do that first we need to create urls.py
in our application directory.
from django.urls import path
from . import viewsurlpatterns = [
path('', views.firstPageIndex,name='firstpage'),
]
Here an example to show you guys.
So views.firstPageIndex
means that we import function firstPageIndex
from the views.py
. So let’s create that function inside views.py
like below
from django.shortcuts import render
from django.http import HttpResponse# Create your views here.
def firstPageIndex(request):
return HttpResponse('Hello, World!')
Here an example to show you guys.
But doing this is not enough to output the Hello, World!
We need to update the root urls.py
with our new application like below.
from django.contrib import admin
from django.urls import path,includeurlpatterns = [
path('admin/', admin.site.urls),
path('', include('firstpage.urls')),
]
Here an example to show you guys.
So actually we are trying to get the applications urls
and if we refresh our page it will output like below.
Now we want to make another page name secondpage
. So let's add into our urls.py
.
path('secondpage', views.secondPage,name='secondpage')
Now we should create one function name secondPage
inside view.py
def secondPage(request):
return HttpResponse('Nothing here!')
Now if we got to the path /secondage
we will be able to see the new output. This is how we can play with view & URLs.
Templates
How about if we want to integrate with bootstrap templates? First, make a new directory on the first page and make a new file name index.html
firstpage
--> templates
--> firstpage
--> index.html
After that please write this inside index.html
Now we want to change the page to render this. To do that just change urls.py
like below
By doing this if we refresh the page it will render the index.html
But what if we want to make the second page to output Nothing here
? Do we need to create another index.html? So to do that we create a new templates directory in root. It will look like this for now.
Now go to settings.py
and add this on top of the script.
import os
After that, we going to add the path of the templates in TEMPLATE
Now we are going to make a base.html
in our new templates directory. This HTML will have the base that we need so the next time we going to create another page we just extend from this. Inside this base HTML just copy the header and footer of index.html
and do like below.
In index.html
we edit it like below.
So right now if we want to make another page name as secondpage.html
we can just do like below.
But we need to update our view.py
Now it will output like below
Static Files
Imagine we have a lot of CSS, js, and others. Where do we store it? and how can we load it? So to do that first we need to create one directory name as staticfiles
in root.
It will look like the above. Now we need to update our settings.py
like below.
Now let's copy from below jsfiddle to put into our web.
Put the whole content of js into one new file we name it as clock.js
Put the whole content of CSS into one new file we name it as clock.css
Now we are going back to base.html
and do some changes like below
# Load static Files
{% load static %}# Get the css & js from static directory
{% static 'css/clock.css' %}
{% static 'js/clock.js' %}
Once done, we can add the HTML tag into secondpage.html
Now if we refresh again we can see the clock :)
Don’t mind about the center haha. I’m bad with HTML >.< . That’s how we can play with static files.
Admin
First, let’s create a superuser to open the admin panel. But before make you sure to migrate first
python manage.py migrate
python manage.py createsuperuser
Once we have input the username, email & password. We can use the admin panel.
Models
Let’s try playing with models. We gonna create simple models to store questions. Please write like below in applications models.py
So imagine we got 10 questions and we store it inside a database to fetch easily using Django. Once we have created a model, please update in admin.py
of the applications like below
After that you guys just need to makemigrations
and migrate
python manage.py makemigrations
python manage.py migrate
Once we done this. We can try to check on the admin panel to check if the model has been created or not.
Let's create questions like below.
So how can we fetch this on the web? So first we need to import our models in views
Then we can fetch the data and put it inside contetxt
which is a dictionary
And we can output it in index.html like below
Forms
To make form first let's wrap our questions with form
tag like below
Now if we want to take this POST
from the page, we need to update in views.py
like below.
Now it will print whatever we input.
SQLite3 (CRUD)
Let's create another form in secondpage
to add new questions. The content will look like below
To start playing with CRUD lets make something like this in secondpage views
#Create
The command to create a new row in our models is like below
p = Questions(question=request.POST['createquestion'])
p.save()
If we add a new one and go back to the first page we can see a new questions been added.
#Read
For this example, it is the same as first page
listofquestions = Questions.objects.all()
context = {'listQuestions':listofquestions}return(request, 'path.html',context)
To read the questions just do a simple loop like below
#Update
For this case, we going to update the fifth questions which are How are you today?
to something else.
Questions.objects.filter(question='How are you today?').update(question=request.POST['updatequestion'])
Now if we go back to the second page we can update to new question.
But make sure to have more columns to specify the uniqueness of the value.
#Delete
To delete the row just write the code below
Questions.objects.filter(question=request.POST['deletequestion']).delete()
If we submit the value, we can refresh the first page to see that last question has been deleted.
Tips & Tricks
- To open the web on the same network
python manage.py runserver 0.0.0.0:8000
- To compare strings
{% if var1.A|stringformat:"s" == var2.A|stringformat:"s" %}
- HTTP Response
With parameter to give ?id=1
and the endpoints look like this http://localhost:5000/result/?id=1
return HttpResponseRedirect('/result/?id=%s' % id)
- URLs with parameter
path('question/<int:id>', views.questions, name="ques")