DJANGO TUTORIAL
In this blog I am explaining about how to create a
basic app using the Django –python web framework, if you don’t know about the Django
framework please refer the blog below,
Reference link : https://mayura-apptech.blogspot.com/2022/07/introduction-about-django-python-web.html
GETTING
STARTED WITH DJANGO:
Requirements:
Python should be
installed
Pip = package manager
CREATING
THE VIRTUAL ENVIRONMENT:
Before you create a project you need a virtual
Environment to isolate the code from the other projects and for the security.
You can create a virtual environment by using the
following syntax,
Python –m venv environment_name
This will create a folder/directory with the environment
name.
You can activate the virtual environment .
Environment name/scripts/actiavte
You can see the result once it is activated.
Output:
PS C:\Users\sugum\OneDrive\my_django>
my_django/Scripts/activate
(my_django) PS
C:\Users\sugum\OneDrive\my_django>
INSTALLING
DJANGO:
You can install django using the following syntax,
Pip install django
CREATING
THE PROJECT:
After creating the virtual environment the first
step is to create the project folder
By using the following syntax you can create the
project folder inside the virtual environment.
Django-admin startprojecrt
project_name
The project folder will contains the following
files,
RUN
THE PROJECT:
Navigate to the project folder , by entering the following
syntax you can run the project on the browser.
Python manage.py
runserver
CREATING
THE APP:
We have a Django
project! The next step is to make an app in your project.
You cannot have a web
page created with Django without an app
Python manage.py startapp appname
I will name my
app blog.
If the server is
still running, and you are not able to write commands, press ctrl+c to stop the
server and you should be back in the virtual environment.
It will create the application folder inside the
project folder with the following files.
All the file in the
folder have specific meaning.
DJANGO VIEWS:
Django views are
Python functions that takes http requests and returns http response, like HTML
documents.
A web page that uses
Django is full of views with different tasks and missions.
Views are usually put
in a file called views.py located on your app's folder.
There is views .py in
my app (blog) folder, I open the views.py file and add the content like below,
from django.http import
HttpResponse
def index(request):
return HttpResponse("Hello
world!")
This is a simple
example on how to send a response back to the browser.
But how can we
execute the view? Well, we must call the view via a URL.
URLS:
Create a file named
urls.py, in the same application folder, and add the code inside the file.
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
The urls.py
file
you just created is specific for the blog
application. We have to do some routing in the project
directory demo as well.
There is a file called urls.py
on
the demo
folder, open that file and add the include
module in the import
statement, and also add a path()
function
in the urlpatterns[]
list, with arguments that will route users that
comes in via 127.0.0.1:8000/blog/
Now run the server you will get the webpage result in the browser.
TEMPLATES:
Templates are used to
define the layout of the webpage , Django follows HTML as the template
language.
Create a templates
folder in the application folder and create a html file inside that for the webpages like below,
Them modify the views.py like below,
from django.http import HttpResponse
from django.template import loader
def index(request):
template = loader.get_template('blog.html')
return HttpResponse(template.render())
then open the settings.py in the project folder and
add our app in the installed apps list.
Then run the server you will get the webpage result
in the browser.
DJANGO
MODELS:
Model means a table inside a database.
SQLite
database:
When we created the Django
project, we got an empty SQLite database. It was created in the demo root folder.
We will use this
database.
Create Table (Model)
To create a
new table, we must create a new model.
In the /blog/
folder, open the models.py
file. It is almost empty by default, with only an import statement
and a comment:
To add a
Members table in our database, start by creating a Members class, and describe
the table fields in it:
from django.db import models
class blog(models.model):
blog_title=models.CharField(max_length=100)
blog_content=models.CharField(max_length=10000)
published_date=models.DateField(max_length=15)
then navigate to the project folder and run the
following comment,
py manage.py makemigrations blog
which will result in,
Migrations for 'blog':
blog\migrations\0001_initial.py
- Create model blog
(my_django) PS C:\Users\sugum\OneDrive\my_django\demo>
Django creates a file
with any new changes and stores the file in the /migrations/ folder.
Next time you
run py manage.py migrate Django will create
and execute an SQL statement, based on the content of the new file in the
migrations folder.
Run the migrate
command:
py manage.py migrate
The SQL statement created from the model is:
migrations.CreateModel(
name='blog',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('blog_title', models.CharField(max_length=100)),
('blog_content', models.CharField(max_length=100)),
('published_date', models.DateField(max_length=15)),
],
),
Now the blog table is
empty we should add the records.
ADD RECORDS:
let's write Python code directly in the Python interpreter
(Python shell) and add some blog in our database, without the user interface.
To open a Python
shell, type this command:
py manage.py shell
it will open a interactive console in the terminal.
after the three >>> write the following
>>> from
blog.models import blog
Hit [enter] and write
this to look at the empty Members table:
Blog.objects.all()
This should give you an
empty QuerySet object, like this:
<QuerySet []>
A QuerySet is a
collection of data from a database.
You can add a blog record by following comment,
>>>
blog1=blog(blog_title='demo_blog', blog_content='demo_content',
published_date='2022-07-08')
then save the values in database,and view the values
if it is saved,
blog.save(blog1)
>>> blog.objects.all().values()
<QuerySet [{'id': 1, 'blog_title': 'demo_blog',
'blog_content': 'demo_content', 'published_date': datetime.date(2022, 7,
8)}]>
ADD
MULTIPLE RECORDS:
You can also add multiple records by making a list
of blogs and execute .save() comment.
>>>
blog2=blog(blog_title='demo_blog1', blog_content='demo_content1',
published_date='2022-07-08')
>>>
blog3=blog(blog_title='demo_blog2', blog_content='demo_content2',
published_date='2022-07-08')
>>> blogs=[blog2, blog3]
>>> for x in blogs:
...
blog.save(x)
...
>>> blog.objects.all().values()
It will give a output like,
<QuerySet [{'id': 1, 'blog_title': 'demo_blog',
'blog_content': 'demo_content', 'published_date': datetime.date(2022, 7, 8)},
{'id': 2, 'blog_title': 'demo_blog1', 'blog_content': 'demo_content1',
'published_date': datetime.date(2022, 7, 8)}, {'id': 3, 'blog_title':
'demo_blog2', 'blog_content': 'demo_content2', 'published_date':
datetime.date(2022, 7, 8)}]>
VIEW IN BROWSER:
We want to see the
result in a web page, not in a Python shell environment.
To see the result
in a web page, we can create a view for
this particular task.
For that we are changing the index template as
follows
Now exit the shell using quit() navigate to the project folder and run
the server
Now you can see the result in the browser.
Comments
Post a Comment