Django With Python
Django With Python
This framework uses a famous tag line:The web framework for perfectionists with
deadlines.
By using Django, we can build web applications in very less time. Django is designed
in such a manner that it handles much of configure things automatically, so we can
focus on application development only.
History
Django was design and developed by Lawrence journal world in 2003 and publicly
released under BSD license in July 2005. Currently, DSF (Django Software Foundation)
maintains its development and release cycle.
Django was released on 21, July 2005. Its current stable version is 2.0.3 which was
released on 6 March, 2018.
0.90 16 Nov
2005
1.8 LTS 1 Apr 2015 Native support for multiple template engines.Supported until at leas
2018
1.9 1 Dec 2015 Automatic password validation. New styling for admin interface.
1.10 1 Aug 2016 Full text search for PostgreSQL. New-style middleware.
1.11 LTS 1.11 LTS Last version to support Python 2.7.Supported until at least April 2020
2.0 Dec 2017 First Python 3-only release, Simplified URL routing syntax, Mobile f
admin.
Popularity
Django is widely accepted and used by various well-known sites such as:
o Instagram
o Mozilla
o Disqus
o Pinterest
o Bitbucket
o The Washington Times
Features of Django
o Rapid Development
o Secure
o Scalable
o Fully loaded
o Versatile
o Open Source
o Vast and Supported Community
Rapid Development
Django was designed with the intention to make a framework which takes less time
to build web application. The project implementation phase is a very time taken but
Django creates it rapidly.
Secure
Django takes security seriously and helps developers to avoid many common
security mistakes, such as SQL injection, cross-site scripting, cross-site request
forgery etc. Its user authentication system provides a secure way to manage user
accounts and passwords.
Scalable
Django is scalable in nature and has ability to quickly and flexibly switch from small
to large scale application project.
Fully loaded
Django includes various helping task modules and libraries which can be used to
handle common Web development tasks. Django takes care of user authentication,
content administration, site maps, RSS feeds etc.
Versatile
Django is versatile in nature which allows it to build applications for different-
different domains. Now a days, Companies are using Django to build various types of
applications like: content management systems, social networks sites or scientific
computing platforms etc.
Open Source
Django is an open source web application framework. It is publicly available without
cost. It can be downloaded with source code from the public repository. Open source
reduces the total cost of the application development.
Cmd
python --version
pip --version
Django-admin --version
django-admin --version
mkdir projects
cd projects
cd new
cd djangpapp
py manage.py runserver
localhost:8000/admin/
After activating it, you should see your virtual environment name
shown in the terminal, as in my example below:
Image by Author
From now on, all the commands must be run with your virtual
environment activated.
A Django project can have one or more apps. You can think of apps
in Django as a way of reusing code between different projects.
The startapp command above created a new folder called films with
some files and a folder inside it. Check them out:
Image by Author
While settings.py is still open, you can change the default language
and timezone for the whole application in
the LANGUAGE_CODE and TIME_ZONE variables.
9. Run the command below to start the local server in the default
port (8000)
python manage.py runserver
or
http://localhost:8000/
Image by Author
11. Notice that a new file called db.sqlite3 was created inside
the films_project folder. That happened because sqlite3 is the
default database configured inside the project/settings.py file.
However, Django allows connections with many other databases;
you just need to make the correct configurations. We won’t talk
more about that now since such a topic is beyond the scope of our
current basic tutorial.
12. There is already another route created by Django for you. First,
be sure that your local server is running (that is, you executed python
manage.py runserver in the terminal and there are no error messages
there). Then go to the admin page and check it out:
http://localhost:8000/admin/
When you tried to access the link below, you probably saw a very
ugly error message, with the information ‘no such table:
django_session’ in the Exception Value field. I wanted you to see
that page because we can learn a lot from the error messages that
come on our way while programming. There is a very easy fix to this:
we only need to run the command to create in the database the
tables that the admin application uses. So:
14. You will also need to create a superuser to log in to the admin
area. Do that with the following terminal command:
python manage.py createsuperuser
Inform the user name, email, and password. Then, restart the server
with the python manage.py runserver , and use your information to
log in to the admin area. You’ll see the following page:
Image by Author
15. Let’s create our first new route, which will replace the Django
default page we have just accessed. We will do that by modifying
the project/urls.py file. Notice that we are also adding a new import
statement to it.
# inside project/urls.pyfrom django.contrib import admin
from django.urls import path
from films import views # added
urlpatterns = [
path('', views.home, name='home'), # added
path('admin/', admin.site.urls),
]
Image by Author
Well done! It doesn’t look fancy at all, but we need to appreciate
what we have achieved here: we created our first webpage using
Django and Python, and all that writing just a few lines of code and
running a few commands in the terminal. Besides, all this
knowledge will help us to create much more complex and exciting
websites in the future, be sure of that. If we build our basis well
enough now, we can become very skilled Django developers in the
future, making great and helpful web applications and having fun
programming with Python at the same time.
I will say it again: the views in Django are where we will create our
controllers, the application logic; it is not the front-end part (these
are called templates in Django). I mention it here because that point
confounds many people, especially those coming from the classical
MVC pattern.
As we can see from what we have done so far, the home function
in films/views.py is concise and straightforward; it just accepts a
Request object as its argument and returns a Response object that
writes a phrase in the DOM and displays it in the chosen URL. But
we could also pass HTML elements to the Response object in a view
function so that the browser would display them with different font
sizes and formats.
html_tags = '''
<h1>This is the Home Page</h1>
<h3>Thanks for visiting us</h3>
<p>MVT means:</p>
<ul>
<li>Model</li>
<li>View</li>
<li>Template</li>
</ul>'''
return response
run python manage.py check to see if there is any error, and then start
the server again with python manage.py runserver. Next, go
to http://localhost:8000 and check the new webpage. Every time
you refresh this page, a GET request is sent to the Django server,
and the home function view is executed. You can check some
information about the Request and Response objects, which we
asked to be printed in the terminal console.
An important warning here: we will NEVER use strings with HTML
tags in our Django production code. Otherwise, we will submit our
application to XSS malicious attacks. So, we will just use HTML
inside Django views in these first examples. Later I will show you
how to use templates in Django to render HTML pages.
20. Fill the films/urls.py file with the new routes information.
# films/urls.pyfrom django.urls import path
from . import views
app_name = 'films'urlpatterns = [
path('', views.main, name='main'),
path('user_info/', views.user_info, name='user_info'),
]
It is now time to start using Django templates. For now, they will be
simple HTML files rendered by the view functions.
23. Create the necessary folders where the HTML files will be saved.
templates/home.html:
<h1>This is the Home Page</h1>
<h3>Thanks for visiting us</h3>
<p>MVT means:</p>
<ul>
<li>Model</li>
<li>View</li>
<li>Template</li>
</ul>
<h3>Link to the website pages:</h3>
<ul>
<li><a href="{% url 'home' %}">Home Page</a></li>
<li><a href="{% url 'films:main' %}">Films Main Page</a></li>
<li><a href="{% url 'films:user_info' %}">Films User_Info
Page</a></li>
</ul>
films/templates/films/main.html
<h1>This is the films MAIN page.</h1>
<h3>Link to the website pages:</h3>
<ul>
<li><a href="{% url 'home' %}">Home Page</a></li>
<li><a href="{% url 'films:main' %}">Films Main Page</a></li>
<li><a href="{% url 'films:user_info' %}">Films User_Info
Page</a></li>
</ul>
films/templates/films/user_info.html
<h1>This is the films USER_INFO page.</h1>
<p>Username: Fabrício</p>
<h3>Link to the website pages:</h3>
<ul>
<li><a href="{% url 'home' %}">Home Page</a></li>
<li><a href="{% url 'films:main' %}">Films Main Page</a></li>
<li><a href="{% url 'films:user_info' %}">Films User_Info
Page</a></li>
</ul>
An important note here: if you visit the pages right now, you will
notice that nothing has changed. That happens because we haven’t
made any updates in our views. We need to make that each one of
views renders the correct template.
27. So, replace all content in films/views.py for the new code below:
from django.shortcuts import render
def home(request):
return render(request, 'home.html')def main(request):
return render(request, 'films/main.html')def
user_info(request):
return render(request, 'films/user_info.html')
Now visit the URLs and note the differences. Navigate through the
links to move quickly between pages.
I don’t know if you noticed it, but the code inside the HTML files has
many repeated lines. That is not desirable at all since it violates the
DRY (don’t repeat yourself) principle, and we need to fix that.
Django allows HTML code that should appear in multiple pages to
be written just in one HTML file, in a very easy way, using template
tags.
We will now use some code from the Bootstrap web design
framework in our project. Unfortunately, I can’t explain here how
basic HTML, CSS, and Bootstrap code work. Otherwise, this tutorial
would be even more extensive than it already is. However, those are
really nice skills to learn if you want to work with web development,
even on the back-end side. New knowledge never hurts, in my
opinion.
So, if you want to know more about how to create nice webpages
interfaces, I suggest that you check out the great course
called Responsive Web Design Essentials — HTML5 CSS3
Bootstrap, by Daniel Walter Scott. The videos are very informative,
the exercises are great, and Daniel manages to transmit his
knowledge in a very effective and fun way.
29. Fill the templates/base.html file with the code below. This will be
the code that will be extended in the other HTML pages:
{{title}}.
Finally, notice the double curly brackets in {{title}}. This is the way
Django has to render Python variables passed by the views to the
templates. We haven’t done that yet, but we will later.
templates/home.html:
{% extends 'base.html' %}{% block content %}<h1>This is the Home
Page</h1>
<br>
<h3>Thanks for visiting us</h3>
<br>
<p>MVT means:</p>
<ul>
<li>Model</li>
<li>View</li>
<li>Template</li>
</ul>{% endblock %}
films/templates/films/main.html:
{% extends 'base.html' %}{% block content %}<h1>This is the
films MAIN page</h1>
<br>
<h4>Some Pixar Movies:</h4><ul>
{% for number in '012'|make_list %}
<li>Toy Story {{forloop.counter}}</li>
{% endfor %}
</ul>{% endblock %}
films/templates/films/user_info.html:
{% extends 'base.html' %}{% block content %}<h1>This is the
films USER_INFO page</h1>
<br>{% if userinfo %}
<h4>username: {{userinfo.username}}</h4>
<h4>country: {{userinfo.country}}</h4>
{% else %}
<h4>username: not informed</h4>
<h4>country: not informed</h4>
{% endif %}{% endblock %}
Notice how each of these three last HTML files starts with {% extends
Now look for errors with python manage.py check and then run the
server with python manage.py runserver. Check how more
presentable our pages are now.
Image by Author
31. Now open films/views.py and replace the old code for this new
version. Then run the server and notice how that change impacted
the information displayed in the page’s title (the text meta
information presented in the browser tab) and in the user
information presented in the user_info page.
Note, for example, how the title variable and its values appear both
in the views and in the base.html template conditional structure.
The home view function passes no title information, so the title value
will be None, and the else clause will be executed, showing the
default title on the home page. On the other hand, both the main and
the user_info views functions have a key 'title' in the context
dictionary, so its value will be ‘truthy’, and the if clause will be
executed, showing the title value in the tag browser when the
template is rendered.
32. Open films/models.py and insert the code below. We will create
our first Django models.
Notice that Django models are created as classes that inherit from
the models.Model Django class. We are creating here two
tables: genre and film, with actually 2 and 4 columns respectively.
We didn’t have to add the id column for each model in our code
because, in the project/settings.py file, the
variable DEFAULT_AUTO_FIELD is configured to create for every model
table an id column with auto-increment integer values.
Notice also that the Film model has a foreign key column
called genre, with a one-to-many relationship. That is not the perfect
relation between these two tables. Still, we are using here a more
simplified model for didactic purposes, since many-to-many models
are more complicated and should be learned in a second moment.
Image by Author
36. Click on the Films link, find the Add Film button, fill in the fields
and save the information. You can add a new genre right on this
page by clicking on the green plus sign next to it. That will insert a
new row in the genre table. Save at least three new movies. I saved
the four Matrix movies, and you can see how their names are listed
nicely in the admin area. I can click on any of them, make changes to
their data and then press the save button. All these changes are
automatically persisted in the sqlite3 database for the Django
application.
Image by Author
37. Now stop the server and run python manage.py shell in the
terminal. The Django interpreter will then be open. This is another
really cool feature: it not only allows you to run Python code with the
interpreter, but it also has all your project files loaded. So, you can
run Django commands here using your project files, such as the
models we have just created.
Image by Author
Now, we will use these new models we created and connect them to
our views so that the database data might be shown on our main
web page from the films app.
40. Open films/main.html and change its content to the code below.
Note how we use a for loop to show all films info saved in our
database.
{% extends 'base.html' %}{% block content %}<h1>This is the
films MAIN page</h1>
<br>
<h4>Films saved in our database:</h4><ul>
{% for film in films_list %}
<li>{{film.title}} ({{film.year}}, genre:
"{{film.genre}}")</li>{% endfor %}
</ul>{% endblock %}
Image by Author
Go ahead and change the parameters’ values, hit enter, and see how
the values will change on the page. Check also the console to see how
the query parameters dictionary is structured. You can get any of its
values using the request.GET.get(KEY) code.
So, before we move to the next page, we need to save the data passed
in the form. We do that by using request.POST.get(KEY) for every
input field, where KEY is the value from the name attribute from the
respective <input> HTML tag, so we cannot forget to set those. Then
we can pass these values to another dictionary located
in request.session, which is extremely helpful. It allows data to be
stored in the current browser session and be retrieved in different
moments by our code. That is why we can use, inside
the user_info view, the information saved in the session dictionary
and display them.
47. Create a new route in films/urls.py. We will only show this line
below, but you already know how to insert it in the file.
(...)path('<int:id>/details', views.details, name='details')
(...)
Notice the new notation <int:id>. the < > signs here show we are
dealing with a new parameter type called route
parameter. int shows that it is an object from the int class
and id tells Django that a primary key is expected here.
This part will be potentially useful for people who want to put
together these two amazing resources: Plotly graphs and Django.
The most important things to note here are the following:
Use the .to_html() method from a Plotly Figure object and save it
in a context dictionary with a name such as fig.
In the Django template, use the tag {{fig | safe}} to render the
graph.
I will use the Gapminder dataset here to speed things up. Since it
has nothing to do with films, it would be the proper procedure to
create another Django app. But I won’t do that. Instead, I will put a
new route outside the films one and borrow films/views.py to store
the view and auxiliary functions necessary to display the graph. I will
also use route parameters to filter the graph by year.
Inside films/views.py, we will add two functions that are not Django
views since they will not process an HTTP request. The
function get_data() only gets the Gapminder dataset
from plotly.express as a Pandas DataFrame. And create_plot() will
generate the famous Gapminder bubble chart. These functions are
called inside the gapminder function view, and the year route
parameter is used here to filter the dataset before generating the
graph.
52. Install Pandas and Plotly with PIP:
pip install pandas plotly
53. Open films/views.py, import Plotly Express and, right after the
last import, define the get_data() and create_plot() functions:
import plotly.express as px# keep the other imports(...)def
get_data():
df = px.data.gapminder()
return dfdef create_plot(df, year):
fig = px.scatter(
data_frame = df.query(f'year=={year}'),
x = 'gdpPercap',
y = 'lifeExp',
color = 'continent',
size = 'pop',
height = 500,
log_x=True,
size_max=60,
hover_name="country")
fig = fig.to_html()
return fig