avatarBryan Dijkhuizen

Summary

This context provides a beginner's guide to creating a simple web application using Python's Django framework.

Abstract

The text is a comprehensive guide on how to create a web application using Python's Django framework. It starts with the installation and setup of Django and Python, followed by creating a new project and understanding the project directory structure. The guide then moves on to running the development server, creating a new app, and defining models for the app. It also covers activating the model, creating a blog page, and using the Django admin interface. The guide concludes with references for further reading.

Opinions

  • The author believes that adding web applications to a website can enhance its functionality and drive audience engagement.
  • The author emphasizes the importance of understanding how to create a web app as a valuable skill for tailoring an app to a specific purpose and improving one's resume.
  • The author recommends using SQLite as the default configuration for the database, especially for those new to databases or interested in trying Django.
  • The author highlights the tedious nature of generating admin sites for adding, changing, and deleting content, and appreciates Django's automation of this process.
  • The author encourages readers to explore and play around with the admin dashboard, implying that it is user-friendly and self-explanatory.
  • The author acknowledges the hard-coding of the page's design in the view and suggests creating a template to rectify this issue.
  • The author hopes that this guide will empower readers with the fundamentals of Django in Python and inspire them to explore further.

How to Create a Simple Web Application Using Python’s Django Framework

A beginner’s guide for creating a web application using Python’s Django framework.

By Reza Namdari on Unsplash

Adding web applications to your website can greatly enhance the functionality of your site, and drive engagement from your audience as they find new reasons to visit.

Beyond this, having an understanding of how to create a web app is a fantastic skill to have. Not only will this allow you to tailor an app to a specific purpose, but it’s also a great thing to have on a resume.

In this article, I’ll teach you how to create a web application with the Python framework called Django. Django is a high-level Python web framework that is both free and open source.

Getting Started With Django

Ideally, you have already installed Python on your device. If you have not yet done this, then you can go to Python’s official website to download the latest version. To check if you are running the latest version of Python, you can run the following command in your terminal/command line:

$ python

It would help if you ended up with something similar to this:

Python
[GCC 4.x] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

To install Django, you need the Python package manager pip. You can download it on the PIP website. When you have a stable installation of pip on your device, you need to install Django by using the following command:

$ python -m pip install Django

Now, Django will be installed in Python. To verify that you have installed Django successfully, open up the Python terminal and import Django:

$ Python
>>> import django
>>> print(django.get_version())

And as I am running version 3.1, I will get the following output:

3.1

Creating Your First Django Application

If this is your first time using Django, you’ll have to take care of some initial setup. From the command line, cd into a directory where you’d like to store your code, then run the following command:

$ django-admin startproject newproject

This will create a new project directory. Please be aware that you shouldn’t use names for your projects that are reserved by Django (such as “Django” or “Test”).

Project Directory Structure

The folder structure should appear as follows:

newproject/
    manage.py
    newproject/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

Here is an overview of the files it contains:

  • The outer-most root directory newproject is the root directory. Its name doesn’t matter to Django. You can rename it as you like.
  • manage.py is the command-line utility that lets you interact with this Django project.
  • The inner newproject folder is the real place for your project. We call this a package.
  • __init__.py is an empty file that tells Python that this directory should be considered as a Python package.
  • settings.py is the configuration file for this Django project.
  • urls.py is where the URLs for the main project are declared.
  • asgi.py is an entry point for ASGI-compatible web servers to serve your project.
  • wsgi.py is an entry point for WSGI-compatible web servers to serve your project.

Running the Development Server

To check if your Django project has been set up correctly, we are going to run the development server with the following command:

$ python manage.py runserver

An important note is that this cannot be used as a production server. This is purely for development purposes only. If you see the following output, your server is working:

Performing system checks...System check identified no issues (0 silenced).You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.September 04, 2020 - 10:13:20
Django version 3.1, using settings 'newproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Now that the server is running, visit http://127.0.0.1:8000/ with your web browser.

Running on Different Ports

If you want to change the server’s port, then you need to pass it as a command-line argument:

$ python manage.py runserver 1602

The same goes for the IP address:

$ python manage.py runserver 0:8000

This will run on IP address: 0.0.0.0

Creating a New App

Now that your environment is set up, you’re set to start doing development. Each application you write in Django consists of a Python package that follows a particular convention.

To create your app, make sure that you’re in the same directory as manage.py and type in the following command:

$ python manage.py startapp blog

This will create the blog directory:

blog/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

Creating a View

Let’s write the first view. You need to open the views.py file in your blog/ directory. Let’s create a simple view as follows:

from django.http import HttpResponsedef index(request):
    return HttpResponse("Hello Medium, this is a new blog post")

To call the view, we need to map it to a URL. Let’s create a new file (urls.py) and put in the following code:

from django.urls import pathfrom . import viewsurlpatterns = [
    path('', views.index, name='index'),
]

Now we have set up the URLs for the blog app, but this isn’t connected to the main Django application. So let’s do that by going into the main urls.py file as follows:

from django.contrib import admin
from django.urls import include, pathurlpatterns = [
    path('blog/', include('blog.urls')),
    path('admin/', admin.site.urls),
]

Now that we have connected a view to the URLs, you can check it out in your browser. Simply rerun the development server to do so:

$ python manage.py runserver

Go to http://localhost:8000/blog/ in your browser, and you should see the text “Hello Medium, this is a new blog post.”

Database

We are going to open the settings.py file to check our configuration. By default, the configuration uses SQLite. If you’re new to databases or you’re just interested in trying Django, I would recommend this option.

If you notice INSTALLED_APPS, you might see that our blog app isn’t in it yet, so let’s do that by adding:

'django.contrib.staticfiles',
'blog',

You can ensure that all tables are created by simply running the database migration as follows:

$ python manage.py migrate

This command will take a look at all the installed apps and create them according to database tables.

Models

We are going to define our models for the blog app. We will create one model and label it “Article” or “Blog Post” (feel free to decide this yourself). Python classes represent these concepts. Edit the blog/models.py file so that it looks like this:

from django.db import modelsclass Post(models.Model):
    title= models.CharField(max_length=200)
    content= models.CharField()
    pub_date = models.DateTimeField('date published')

We can see that every class inherits the class of Model. Each model has several class variables, each of which represents a database field in the model. To get more information about the Model class, I would recommend that you refer to the official Django documentation.

Activate the Model

That small bit of model code gives Django a lot of information. With it, Django can:

  • Create a database schema for this app.
  • Create a Python database-access API for accessing the Post objects.

To migrate, simply run the command:

$ python manage.py makemigrations blog

You should see an output similar to this:

Migrations for 'blog':
  blog/migrations/0001_initial.py
    - Create model Post

By running makemigrations, you’re telling Django that you’ve made some changes to your models. To run the SQL code to import into your database, run the following command:

$ python manage.py sqlmigrate blog 0001

You should see something like this:

BEGIN;
--
-- Create model Post
--
CREATE TABLE "blog_post" (
    "id" serial NOT NULL PRIMARY KEY,
    "title" varchar(200) NOT NULL,
    "content" varchar() NOT NULL,
    "pub_date" timestamp with time zone NOT NULL
);COMMIT;

To migrate your database for the last time, run the migrate command as follows:

$ python manage.py migrate

Django-Admin

Generating admin sites for your staff or clients to add, change, and delete content is tedious work that doesn’t require much creativity. For that reason, Django entirely automates the creation of admin interfaces for models. To put this in place, we’ll first need to create a user who can log into the admin site. Run the following command:

$ python manage.py createsuperuser

Enter your desired username and press enter:

Username: admin

You will then be prompted for your desired email address:

Email address: bryan@dijkhuizenmedia.com

The final step is to enter your password:

Password: **********
Password (again): *********
Superuser created successfully.

The Django admin site is activated by default. Let’s start the development server and explore it. When you go to your Django site and go to /admin, you will see a login screen. Enter your credentials and you will be redirected to the dashboard:

If we want the blog app to be configurable in the admin dashboard, then we need to register it to our admin.py file:

from django.contrib import admin
from .models import Post
admin.site.register(Post)

You can look around and play with the admin dashboard (it’s pretty self-explanatory, I believe).

Creating a Blog Page

First, create a new view in blog/views.py:

def post(request, post_id):
    return HttpResponse("You're looking at post %s." % question_id)

Now configure the urls.py to be able to use this view:

Take a look in your browser at /blog/<post_id>/. If you have added posts in the admin dashboard, then this ID will be displayed. Now, let’s create a view that displays the blog posts. In the blog/views.py, we add the following code:

from .models import Post
def index(request):
    latest_post_list = Post.objects.order_by('-pub_date')[:5]
    output = ', '.join([q.question_text for q in latest_post_list])
    return HttpResponse(output)

There’s a problem here, though: The page’s design is hard-coded in the view. To rectify this, we will create a template. First, create a directory called templates in your blog directory. Django will look for templates in there.

Put the following code in that template called index.html:

Now let’s update our index view in blog/views.py to use the template:

Conclusion

I hope you learned a lot from this beginner’s guide to setting up a simple web app in Django with Python. My aim in writing this article was to outfit you with the fundamentals of Django in Python, thereby empowering you with the ability to get curious and play around from there. Hopefully, this article has helped you progress on your web development journey.

Feel free to leave any thoughts in the comments. Thanks and happy coding!

If you enjoy reading stories like this and you want to support me, consider signing up for a Medium membership. It will only cost you $5 a month — this will give you access to all stories on Medium! If you are going to use this link, I will earn a small part of that, besides that, if you want to stay updated when I post a new story, you can signup for my free newsletter here!

References

More content at plainenglish.io

Programming
Python
Web Development
Software Development
Software Engineering
Recommended from ReadMedium