My Introduction to Django
Randy Steele
Posted on March 12, 2021
My Introduction to Django
I have been itching to learn something new lately so I decided to give Django a try. I have heard a lot about Python and Django but I hadn't yet delved into it. I will show you how I created a simple Django wordcount app.
First things first.
First, you need to see if you have Django installed on your computer. To do this I just decided to run the command to install Django which is pip3 install django
and I received
this: Requirement already satisfied: django==2.0.2 in /usr/local/lib/python3.9/site-packages (2.0.2)
so it looks like I already have it installed, if you don't have it installed, this command will get it installed for you.
Creating a Django project
Django comes with some commands that simplify things for you. Similar to how you can run rails new myapp
with Django you can run django-admin startproject myapp
to see the other commands Django comes with just run django-admin help
in your terminal. When you run this command you will get a file structure that looks a little like this
Starting the Django server
To verify everything went well when you created your new project, you can run the server by running python3 manage.py runserver
you should get a response like this
March 12, 2021 - 16:58:53
Django version 2.0.2, using settings 'wordcount.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
If you have ever run a server before this should look familiar, just go to this URL, and if you see the Django homepage you are good to go!
Templates
Here's how Django defines templates:
A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted.
Create a new folder in the top level of your directory named templates
and within that folder create a file named home.html
within that file <h1>HELLO</h1>
Once you have done that you will need to create another file named views.py
in this file, we need to tell Django what template we want to render. That code should look something like this:
from django.http import HttpResponse
from django.shortcuts import render
def homepage(request):
return render(request, 'home.html')
This tells Django that when we visit the homepage we should render the home.html
template. Next, navigate to settings.py
and find TEMPLATES
and then DIRS
and add 'templates'
that should look like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Finally, navigate to urls.py
and urlpatterns
and modify it like so:
urlpatterns = [
path('', views.homepage),
]
For those of you that are familiar with rails, this is kind of like setting up your routes.rb
file. Now let's fire up the server python3 manage.py runserver
and you should see your home.html
file rendered.
My App
The app I built is a wordcount app. So, in my home.html
I have built out a form with a button that will fire the event to count the words in a text box. So, in my home.html
I have build the following form:
<form action="{%url 'count' %}">
<textarea cols="40" rows="5" name="fulltext"></textarea><br><br>
<input type='submit' value="Count!"/>
</form>
I then created a count.html
file in the templates
directory that will be responsible for rendering the HTML on the count page. Perhaps first we should navigate to our views.py
file and configure the count view. I will create a new view called count
and in that view, I will grab the value of fulltext
which is the name
of the Textarea field. Next, in order to count each word in the text area box we will split the fulltext
and add that to our return.
def count(request):
fulltext = request.GET['fulltext']
wordlist = fulltext.split()
return render (request, 'count.html', {'fulltext':fulltext, 'count':len(wordlist)})
Conclusion
That's it, you should now have a working Django wordcount app. I come from a Ruby background and I can see some similarities between Python/Django and Ruby/Rails. Some examples are the code in views.py
looks a lot like a Ruby method without the end
the urls.py
is similar to config/routes.rb
and of course the html
files are similar to the views in Rails. Overall I think Django has been pretty simple to get started with and I could definitely see myself using it more often.
Resources
Learn more about Django here and go build something fun!
Feel free to check out the repo here
Posted on March 12, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.