0% found this document useful (0 votes)
11 views65 pages

Noor-Book.com Django Web Framework Simple Project

Uploaded by

Abdo Antr
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)
11 views65 pages

Noor-Book.com Django Web Framework Simple Project

Uploaded by

Abdo Antr
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/ 65

1/11/2021

Django Web Framework


basic knowledge and
Practice

ABMA
Content:
Title Pages
Important things to do before beginning the lesson 1-7
Installing Django web Framework inside a virtualenv 8
Installing pillow package inside the virtualenv 8
Installing Django crispy forms inside the virtualenv 8
Creating a project through using the Django-admin 9
command line
Renaming the container folder to something different 10
than the project name.
Creating a new application through using the python 11
manage.py command line
Configuring Files in project Folder 14-19
Configuring Files in app folder 20-21
Running the Server in Django 22
Collectstatic command line 23
Migrate and makemigrations command lines 24
Create Superuser and changepassword syntax in 24-25
Django
Creating a new model in models.py in the app folder 26-29
and making migrations of models into the database, in
this case, SQLite3
Basic Configuration For Templates 30-33
Dealing with Paths in urls.py and views.py in app 34-43
folder. Creating a simple page.
Adding simple page to check login and authentication
for existing users.
Adding a new page to allow registration 44-50
Creating forms.py file and creating a form based on 51-63
Model…. For this scenario, model name: Feedback.
Saving the form, updating a specific record of the
feedback model using forms.py

Page | 1
Installing Python:
To install python first, you need to visit, www.python.org to be able to download the
latest version, and currently, python 3.9 is available. Make sure to select the path during
installation to be added.
Checking python version and pip in windows:
To check the version of python and make sure it is working fine, we can issue the
following commands respectively:

If you get results back, it means they are working perfectly, if you want to update pip, you
can issue the following command for update:

As you can see, after issuing the command above, the update started and it turned out the
one currently installed is out of date and automatically, python removed the old one and
installed the new.
To check the list of packages available and installed already, we can issue the following
command:

Page | 2
It seems we have a lot of packages installed, so the question here is how can I install and
uninstall package in python…. Suppose you want to install virtualenvwrapper-win, what is the
right command to install this package?

The command line highlighted in green is the one to use. Therefore, it is already installed,
that is why we are getting the requirement is already satisfied.
To uninstall, we simply change the word install to uninstall as it shows below:

Page | 3
We didn’t execute the uninstallation command because virtualenv is one of the key limits in
learning Django web framework since it gives you the flexibility to work on more than one
project at the same time. That is, if you install the Django web framework globally, it means
you can only work on one project at a time. To resolve that issue, the virtualenv here comes
to help.
Creating a new virtualenv to work on:
To create a new virtualenv, we must keep in mind the following command lines:
 mkvirtualenv
 lsvirtualenv
 workon <virtualenv_name>
 deactivate
The above commands are important to deal with virtualenv…. Let’s now creating a new
virtualenv and call it example and apply all the previous command lines to see how to work
with:
- mkvirtualenv:

Directly after issuing the command, you will see that we are already inside the
example virtualenv…. To view the content of packages installed already inside, we can
issue the command pip list:

Page | 4
Even though we have already updated the pip globally, but it looks like it is not
updated in the example virtualenv. Also the list is almost empty except for setuptools
which comes automatically with pip and python inside. That means, the virtualenv is
completely separate from the global settings of Python, and that is the beauty of it.
- lsvirtualenv:
lsvirtualenv shows you all the available virtualenv environments and this command is
important because it tells which one you want to work on. To issue this command, we
can issue the following command line:

The command highlighted in Green shows the command to list down the virtualenv
and the one in yellow indicates which one you are already inside.

- workon and deactivate:


workon and deactivate are commands to activate a virtualenv or deactivate it
respectively. In the previous example, we are currently connected to example
virtualenv, to deactivate, we simply issue the following command:

The one highlighted in red indicates deactivation of the virtualenv and to activate
again, we can issue the command line in yellow as it appears. Notice when you

Page | 5
activate virtualenv, you get the name of the virtualenv between brackets, that is the
sign you are currently inside the virtualenv

With this illustration, we have concluded the basics of python, pip, and
virtualenv package. It is important to give a little insight about them before
moving to installing the main packages we need of this lesson….. Continue to
the next page:

Page | 6
Installing Django web framework, pillow, and crispy form packages
respectively:
To install packages, we must make sure we are connected to the virtualenv we
initially created for this lesson, which is example.
Installing Django:

Installing Pillow:

Installing Crispy Forms:

Checking the current packages installed on our virtualenv example:

Page | 7
All installations have been completed successfully. Note, if you install or create a new
virtualenv, you will need to update the pip through the command:
python –m pip install –upgrade pip

We can now start our Project and App Creation through Django Web Framework

<<<<<<<<< Continue on the next page>>>>>>>>>>>>>>

Page | 8
Creating a new Project in Django Web Framework:
Before starting there are couple of things you need to keep in mind:
1- When creating a Django project, the containing folder will have the same name as the
project name, therefore; it is recommended to rename the container folder to be
different than the project name….
2- You need to go to the location in your computer where you want to create your
project. In my case, I am currently on root C drive, which means when I issue my
command to create a project, it will be added to the C drive.
Creating a Django Project and naming it project:

The green highlighted portion of the command is the syntax and the red one is the name of
our project…. As you can see, we didn’t get any message. Since we are in the C drive, we can
display the content of the drive C and see our container folder… which is by default the same
name as the project.

Page | 9
As you can see, the red highlight shows the container folder name, and the green highlighted
is the project name, to make sure we don’t have confusion, it is recommend to rename the
container folder to something else other than the project name… Let’s name it container:

We renamed the project folder container from project to container, and that is to make sure
we don’t get confused between the parent folder and the project folder.
Creating an app in our project:
Project folder containers the files and configurations that control the apps created. So to
create an app, we will need to use the manage.py file. First, we must change our path to be
inside the container folder to have access to manage.py file:

Page | 10
After moving inside the container, we issue the command:
python manage.py startapp app
app is the name of our application folder
<<<<< With this, we are done with the basic installations of the packages we need for
our lesson…. Please keep reading to see more about Django Web Framework>>>>>>>

Page | 11
Opening our container folder in VSCODE:
Visual studio code is the most popular editor used nowadays by most developers in any
coding language and since it is the recommended one, we can open our container in visual
studio code.
We can go to container folder in DOS window and type code . or simply open visual studio
code and open the container folder from there.

After visual studio starts, we will see on the left side, the container folder and the sub
folders, which are the project folder and app folder we created during the initial step up of
our Django project. Please view the following picture to understand:

Page | 12
Before starting to configure the project folder files and the app folder files, we need to
create two more folders under container folder. The two folders will be named:
- templates
- static
Templates for holding the html pages. Static for holding the static files displaying such as
images and files.

Page | 13
Now, we can start configuring the files on project and app.

Project settings.py and urls.py Configuration:

Page | 14
settings.py:
There are couple of things we need to pay attention to during this configuration.
DEBUG True
ALLOWED_HOSTS = [] For developed, [‘*’] for deployment
INSTALLED_APPS We should add the name of our app at the
end of the list and also, crispy forms too
TEMPLATES os.path.join(BASE_DIR, ‘templates’)
TIME_ZONE =’UTC’ Set it to your local time, in my case,
‘Asia/Muscat’
STATIC_URL= ‘/static/’ Should be left the same
This part to be added to the settings.py file
STATICFILES_DIRS=[
os.path.join(BASE_DIR,’static’)
]

STATIC_ROOT = os.path.join(BASE_DIR,’assets’)
MEDIA_URL=’/media/’
MEDIA_ROOT= os.path.join(BASE_DIR,’media’)

Please view the following pictures step by step to know what should be done in order:

1.
Check for import os, if it doesn’t exist in the settings.py file, add it because it is
important for calling other files as you will see below.

2.

Page | 15
DEBUG should be kept True during development, when you move to production and
deployment, it should be turned to False. Same rule applies for ALLOWED_HOSTS, it
should be kept the same, but when moving to production, it should be:
ALLOWED_HOSTS=[‘*’]

3.
INSTALLED_APPS is where you add the name of your apps, and keep in mind in one
project, you can have as many apps as you want. It is not specified to one project
only. You can add as many as you want here. If you notice, we added the app name
and also, the crispy_forms package as well. Some packages required to be added
here to work, as for others such as pillow, it is only used as an assistant package to
connect to the database.

Page | 16
4.
In the TEMPLATES, we can see the highlighted code we added, that is the only thing we
should do here, it can be templates or any other name, but whatever name you put, it
should match the directory referring to in the container folder.

5.
TIME_ZONE=’UFC’ should be changed to the time zone matching your local time, in my
case, it is ‘Asia/Muscat’

Page | 17
6.
As you can see, the remaining lines have been added, but the media doesn’t exist, it
will be created when retrieving information from the database, so it is playing the
virtual folder we need to view the retrieved data and objects, whether data or
pictures.

<<<< With this one, we conclude the settings.py initial configuration, let’s move
now to the urls.py file and set the initial configuration for it as well >>>>

Page | 18
Urls.py file in project folder initial configuration:
The code here will not be as much as the one we did in the settings, but the syntax is
a little bit complicated since to do so, we must be aware of some packages that need
to be called to execute the command lines. Let’s take a look at the first written codes
without editing of the urls.py file:

We need to import include because we will be including the urls.py file of the app
folder to be seen by the project folder url.py. we will also import packages that allow
us to see the static and media files in case if the settings.DEBUG is True….
Let’s take a look at the code after editing:

Page | 19
Setting the urls.py for the app folder:
urls.py doesn’t exist in the app folder, which means we must create.
Creating the urls.py file:
The urls.py doesn’t exist in the app folder, therefore, we must create a file and name
it urls.py:

After that, we open the urls.py file, and add the following command lines or copy the
initial code in the urls.py in the project folder and paste it in the new urls.py with
some changes. But we will write the code instead for this purpose:

Defining views (index view):

Page | 20
To define the view, we must go to views.py file and click on it to open, before writing
the code, we must import some packages that we need to use later in this lesson.
Here, we will be viewing most of the packages we need for the entire lesson inshallah:

After finishing these settings, we must run the server to see if we get no errors…. We
must open the terminal and here is where to go for it:

After clicking the new terminal, we will be getting the following window:

Page | 21
Running the server to see our work:
To run the server, we must go to terminal, under the container folder, we use the manage.py
file to run the server, and we must also make sure our virtualenv is connected as it appears
in the following picture:

As you can see, the server is running with some unapplied migrations, to view the page, we
can either type:
- Localhost:8000/
- http://127.0.0.1:8000/

Page | 22
Collectstatic command line:
Collectstatic is mainly used for creating the static_root folder, and mostly, it is for
deployment. To before this task, all you need to do is perform the following command line:

The moment we issue the command line, we will get a new folder called assets, and if you
recall, we set the STATIC_ROOT to this folder in settings.py project folder. It is very import
during deployment, it copies all the static files into the assets folder. For example, if you add
a new file to static folder while your project is up and running in product, it means you must
apply this code to ensure the collection of the new added static file into the assets folder,
otherwise, your website wouldn’t be able to see it.
We will see more about collectstatic later when we make a tutorial about a deployment of
another project to see how it can be used and applied.

Page | 23
Migrate built-in models in Django Web Framework:
This is a very initial step to do, and to make it happen, we should issue the following
command line highlighted in green:

After making the migrations of the built-in models, we can then create a super user, the
controlling user of the entire website we intend to make:

Page | 24
As you can see above, the user got created. This is the super user of the project…..
To change the password of the superuser Ahmed, can issue the following command:
Python manage.py changepassword <superusername>:

Note:
You wouldn’t be able to create or change password of the superuser until you issue the
command: python manage.py migrate. Because the models and classes must be created first
in the database. Otherwise, it will give you back an error. Please keep this in mind.
Viewing the admin.py through the browser:
To view the admin feature, we can simply run the server, and type:
http://127.0.0.1:8000/admin or localhost:8000/admin
it will automatically open the admin page for you as it appears in the following picture:

Page | 25
When you providing the superuser name, which is ahmed in this case, and the password
associated with it, you will be redirected to the admin page, which contains the full control
over the entire website as it appears in the picture below:

<<<<<< Moving now to creating a model in models.py in the app folder >>>>>>

Page | 26
Creating a simple model in models.py in app folder, the application:
To create a model, we must be aware of the fields and types we need to use and how to
declare them. In the following example, we will be creating a simple model composed of
three fields:
- ID int, and it is auto incrementing by Django….
- Fullname and it should be a string, type CHARFIELD
- Phone and it should be an integer, type INTEGRFIELD
- Birthdate and it should be a date, type DATEFIELD
- Recorddate and it should be added automatically using, type DATETIMEFIELD
For this model, we will name it Data
Please view the following diagram to form more understanding:

Explanation:
ID field not added because it is by default added to any model created and it is auto
incrementing by 1.
Null=True and blank=True, this means if no data are provided for that specific field, it
wouldn’t give back an error. But if they are not specified, they are by default set to False.
verbose_name is the title of the field when displayed using the crispy form. There is a
feature called forms and when it is in use with a model, verbose_name becomes handy.

Page | 27
Max_length=100 is a CHARFIELD and it must be specified. We don’t need to specify the max
length if we are using the TEXTFIELD. But since we are dealing with a short string field, we
must specify its maximum length.
Def __str__(self) is a function that display the object as the fullname. If we don’t specify
this function, we will only see our saved objects as objects with numbers next to them. This
one avoids you that conflict and allows to know which is which. We will be able to explore this
feature more as we move to admin.py file.
When we are done with writing down the model and saving it, we can now test its migration
to the database, in case if we have an error, Django web framework will tell us what went
wrong. Let’s issue the makemigration command line to declare our new model in the
database:

As you can see, we used two command lines, the first one: python manage.py
makemigrations allows us to create the model data. The second one: python manage.py
migrate, allows us to apply the migration and set it. It is important to keep these two
commands line because each time you apply a change to your model.py, you need to
run these two commands to take effect.
Let’s quickly create a record in the model Data through the shell command:

Page | 28
The green highlighted portion is the code written and the red one is the result of the code.

Let’s add a record into the Data Model and then view:

Green color highlights the code for saving the record.


Light Blue highlights the code for viewing the record based on a condition of the phone
number.
The red color highlights the results of looping the view record object.
Note:
During creating the record, we didn’t specify the date for the record date field because it is auto recording based
on the initial declaration of the model….. auto-now-add=True>>>

Page | 29
Templates
 Setting the layout.html
 Setting the subfolder for the rest of the html pages.
 Creating a simple page to display the information we have on Data Model

Page | 30
Creating the layout.html Page:
The layout.html or what might refer to as the base.html page is the page that will hold the
overall design for the rest of the website. Meaning, the look and decoration on the layout
page will be seen everywhere through the website.
First let’s create a subfolder and call it pages under templates folder:

After creating the subfolder pages, we can now create a new file and call it layout.html and it
should be under templates directly, not inside subfolder pages:
As it appears below:

Page | 31
As you can see to the left, we have a blank layout.html page that we will set its html code
next. The point you should keep in mind here is that the layout or base page should be
located under the parent directory templates, as for the rest of the pages, we can place
them in a separate subfolder directory, for organizational purpose, nothing. It helps you
keep track of your pages, codes, and troubleshoot more easily in case of an error
occurrence.
Setting the HTML CODE in the layout.html page:
To set the html code, we can simply type ! Followed by tap key to display the initial code of
html5 as it appears in the following picture:

As you can see, we got the initial necessary tags we need to work on an html page. Now, we
will add couple of things:
- {% load static %} this one is to allow the call for urls in case if we will insert links
connected directory to our website.
- {% load crispy_forms_tags %} this one is to allow for crispy form package to work
in case if a form.py model is used
- {% block content %} this one is to specify the content of the sub html pages to edit
their content inside.
- {%endblock content %} this one is to specify the end of the block content
Please view the following image to see how it will appear:

Page | 32
The highlighted portion in green is the code we added to the layout.html page. We can also
use the bootstrap either locally or via the internet since they are available and free to use,
and for this lesson, we will be using an online bootstrap and it will be bootstrap4 to match
the type we specified for CRISPY_TEMPLATE_PACK in the settings.py file in the project folder.

To find bootstrap3 or 4 CDN, you can search it in google and all you need to do is adding the
links under the head tag as it appears in the diagram above highlighted in green.

Page | 33
Learning auth,
User in Django
Web Framework
 Auth.authenticate function
 Auth.login function
 Auth.logout function
 Registering a new user in Django Web Framework
 Display Data Model Records on html page

Page | 34
Creating an index html page to view the data of the Data model we created earlier:
First, we need to add a new page under the subfolder pages and call it index.html. in this one,
we will need to do any html tagging except inside the block content if we want to… Here is
the look of the index.html page:

The highlighted portion of code, which basically forms everything written on the page is the
code we need for now…. Under the block content, we can add what we want…. But before
dealing with code, we must test if the page is working or not… So for this reason, we will add
a simple line “ Welcome to my home page” and make it appear at the center and change the
code in the index view to use return render instead of return HttpResponse because now
we have an html page to load instead of a simple text:

Page | 35
Now, we will move to the views.py file in the app folder and alter the cod to be able to call the
new index.html page:

We can now run the server and see if the effect took place:

Now, we know the code is working…..


Let’s now display the information we saved in the Data model, which is only one record and
try to display them on the index page.

Page | 36
The highlighted portion in green is the part we added after removing the initial code line,
which was return HttpResponse (“Hello World!!!!”)
Explanation:
data = Data.objects.all() stands for selecting all the information in the model into an object
called data.
Context ={‘data’: data} stands for the dictionary we created to be able to use on our page.
Return render(request, ‘pages/index.html’, context) stands for the return statement
replacing return HttpResponse and inside, we specified the path of the index page and also,
included the context dictionary since we will need to use it to display the information inside
the page as it will be explained in a moment.
Displaying the data object information in the index page:
To display the information, we must first design a table that will show the distribution of
information evenly across the page and for that, we will create a table in the index.html page
to view instead of the div container and div row and div class:

Page | 37
Let’s test the page now and see if we can view the information or not:

We have two records in the Data model and it is displaying now, if we remove the records
inside, we can see the alternative massage, which is as it appears below after removing the
data:

If we run the server again, we will see the page displaying no data after removing the
records from the Data Model:

Page | 38
Creating a Login Page and Testing Authentication Using auth, User classes under
Django.contrib.auth.models:
One already built-in feature in Django is the ability to create the admin and users in a ready
models that have full control over the page. For this reason, we will be creating a new html
page and call it login.
Login.html page:
Under subfolder pages, we will add a new html file and name it login.html as it appears in the
following picture:

As for the initial step up of the code in the login.html, it should have the extension of the
layout.html page in addition to ability to load static and crispy forms as it appears in the
following picture:

Page | 39
Creating a simple form inside the login.html page to check username and password:
To create a form that can check username and password, we will write the following html
code inside the block content:

Explanation of the highlighted portion:


- Method=”POST” is the method we usually use to post data for checking, saving, and
it is the most method used. It also keeps the information hidden during the process.
- {% csrf_token %} is a Django code to inform Django the form will be using the data
inside the form for checking or saving.
- Name=”username” and name=”password” is what we will be using for checking
against the database. When we move to the views.py code establishment, we will
explain how these name variables can be handy.
- {% url ‘index’ %} is the way Django moves from one page to another… this is the
importance of {% load static %} at the stop of the page. If we don’t include {% load
static %}, this code will result in an error.

Page | 40
Let’s now define the path of login.html in urls.py and then, make the logging view in
the views.py file:
Adding the path for login.html in urls.py file in the app folder:

The highlighted portion of the path is what we added for the login page, note, name=login is
the url during calling in html pages, for example: {% url ‘index’ %}
Adding the login view in the views.py file in app Folder:

Now, we can run the server and see our login.html page:

Page | 41
Even though the html page requires a little bit of organization, but remember the goal here
is to learn how to manipulate the code and be able to understand. Now our page is up and
running, let’s head to the views.py and edit the login view with the following code for
checking and also displaying the status depending on whether username exists or not:

before explaining the the code above, we must know the class or perhaps the page we use
here for checking is Django.contrib.auth.models import auth, User
It will also be used for creating new users and also, maintaining a login session after logging
in. So it is one of the strongest features available in Django.
Code Explanation:

Page | 42
- If request.method ==”POST”: is the condition we are basing the rest of the code on.
Meaning, when you click on the Check button on the login page, first it will collect two
variables:
1- Username: username = request.POST[“username”]
2- Password: password = request.POST[“password”]
3- Then, use the auth.authenticate to run the username and password against the
existing users in the User Model in the database.
4- Saving the checking in a variable user_check.
5- If user_check is true, meaning it contains data inside, then the message will show
there is an existing user or the user exists. Otherwise, it will give a message the
user doesn’t exist.
Let’s Run the page now and test if it will work or not:
Using the admin username to see if it will confirm its existence:

we only have one user registered, which is the admin user. So if we try any other username
and password, we should get doesn’t exist message:

Important tips about auth class in Django.contrib.auth.models:


We will be using auth class in:
- Authenticate
- Login
Page | 43
- Logout
These three functions are the main ones we will be dealing with when it comes to the auth
class.
As for User, it is mainly used to check the existence of a user in the User model and most
importantly, for login or take the user ID to add to a record related to the member.
Creating register.html page to allow new Members to login:
In this portion, we will be talking about how to create a registration page. But before that, we
need to be aware of the following fields, The User model under Django.contrib.auth.models
consists of the following fields:
-first_name CHARFIELD
-last_name CHARFIELD
-email EMAILFIELD
-username CHARFIELD
-password HASHED USING MD5
-is_active BOOL default True
-is_staff BOOL default False
-is_superuser BOOL default False
-last_login DATETIMEFIELD
-date_joined DATETIMEFIELD
The red fields are not to be included during the creation of a new member user. Because
they are the responsibility of the admin to give control or not. As for being active,
date_joined, and last_login, they are set automatically by Django web framework.

Page | 44
Creating register.html page and setting the form that will accept our five fields to
create our new user:
We will first set the page register.html and write down the initial code as the rest of the
pages:

Now, we will add the code that allows us to insert a form composed of five fields:
 First_name
 Last_name
 Email
 Username
 Password
 Confirm password >>>>> this is an additional none model field, for the purpose of
ensuring the password is exactly what is intended.

Page | 45
Page | 46
We have created a form for registration, after finishing this one, we can move to both
urls.py and views.py in the app folder to define the remaining parts to get this page running.
First we will add the view and the path without including the code handling in terms of
checking and subscription to make sure we don’t have errors:

Urls.py file register code:

Views.py register code:

Page | 47
Now, we can test the page and see how it looks after typing, python manage.py runserver
and checking: localhost:8000/register

We are set now to go to the views.py file and write down our code to post the values for the
form fields and perform some checking against the table in the database, and then, save the
record if all conditions are met.
Register view additional subscription code:
Editing the register view will be about getting the values first from the form… checking the
existence of username and also, the email, if any of the username or the email already exist
in the database, the subscription will not complete. Otherwise, it will continue and collect the
values and create an object called new_register and then, save it. If the two passwords don’t
match, it will also refuse to save as we can see in the following screen shot:

Page | 48
After saving, we will run the server and see if we can make it work as we desire or not, in
case of an error, we will modify accordingly.

Page | 49
This is when we try to register with a username that is already registered in the
Django.contrib.auth.models.User
The same thing will happen if we type in an email that is already register. If you notice, we
are using try: and except: and these are to make sure if something goes wrong on the page,
he will get a result back, it wouldn’t give an error page. For example, if we click register
without typing anything, the form will give an error because there is no username, and in
this case, to avoid that we are using try and except.
The page if we click register without typing anything inside the form:

Page | 50
Creating forms.py file in the app folder to automatically display on a page:
Before starting the creation of forms.py file, we must make a model and for this scenario,
we will name it: Feedback

The model Feedback has been saved, now, we must perform makemigrations and then,
migrate for the model to be set in the database:

The Feedback model has been added to the database.


Now, we can create the forms.py file and start its configuration:

Page | 51
Now, we will create a form for the Feedback model, please view the following snapshot to
see how it can be done:

We must now create feedback.html page, path for the feedback.html, and also the feedback
view to handle the code and the form on the feedback.html page:
Feedback path in urls.py file in app:

Feedback code in views.py file in app:

Page | 52
Note:
Since we are using Feedback Form, we must call import it from .forms, and dot refers to the
same folder, which is in this case app folder. So it appears from .forms import
FeedbackForm
Setting the feedback.html page:

Page | 53
Notice the code below {% csrf_token %}, it is using the form we displayed on the page, and
created a submit button to do the action, which will trigger the view to work. Let’s now run
the server and view the page:

Let’s try to insert title, email address, and content for the feedback page, and see if it will
work, notice the star next to each title, a star stands for required here: if we change
blank=True, then we wouldn’t see it because blank stands for required. Let’s try to save a
feedback now:

Page | 54
It is working fine…. But Let’s add some additional features and this time, use the bootstrap to
define the page into two major columns, one holding the form and the other one, for
displaying the feedbacks to see if we are making any change or not… This might be
understood more if we view the following changes we will make:
Editing feedback view Code:

The highlighted portion is the code we added to the feedback view…


Editing feedback.html page:

Page | 55
Let’s now run the server and see the page, and it should display the current saved feedbacks
on the page, and for this purpose, we will add a new one to see how it looks on the page:
Page | 56
Let’s now add another feedback and see how it appears on the page:

As you can see, we got the thank you message and we automatically saw the new feedback
get displayed on the page.
A very import tip about forms.py configuration when it comes to ModelForm:

Page | 57
The form.py scenarios are more, but these are the basic ones you need to keep in mind, and
must also know the exclude should only be used when you are excluding fields that are not
set to False in the bank option in the model.

Editing a specific Feedback:


This part will show you how to take a specific feedback and edit. That means, a specific
selection will be made. In this case, we will be adding a new path, view, a button on the
feedback page to select a specific feedback to edit.
Adding the path in urls.py file:

Page | 58
Adding the edit_feedback view in the views.py file:

- pk: it is the ID of the feedback record, and it is taken from the feedback page and we
will see how it will be written in the url link.
- Instance: instance stands for the record and it is used inside the form to select only
the targeted record based on pk, which holds the ID.
- request.POST, request.FILES, instance=feedback: request.POST is for text,
request.FILES is for images and files upload. Instance=feedback, to make the form
only display the information related to the selected feedback.
Creating the edit_feedback.html page:

Page | 59
After setting the edit_feedback.html page, we can now go to feedback.html page and add a
link that takes the specific record we want to update to edit_feedback.html page as we will
see in the following screenshot:

Page | 60
The highlighted portion of the code is the one we added into the feedback.html page and it is
simply a link to edit_feedback.html page, but inside the link, you can see we specified the
feedback.id and that stands for the pk defined earlier in the view.
Let’s run the server now and see if the code is working or not…
Feedback.html page after adding a button:

Edit_feedback.html, viewing the third comment:

Page | 61
If we type “This is the third comment in the content, and then click update, we will be
redirected to the feedback.html page, and we will notice the update, and also, a message
saying you have updated <feedback title> followed by successfully, as it shows in the
following picture:

Page | 62
With This final part, we conclude this long lesson and
there will be more about:
- Login and logout…. Separate lesson.
- creating an update password page.
- Deleting an account by the user
- learning how to use shell command lines
- learning more about aggregate functions in Django and how
we can use the functions to give results.

I hope this lesson has been beneficial 


Best regards………………………… ABMA

Page | 63
Page | 64

You might also like