Build A Web App Using Django
Tags: python, django, beginners, programming
Published: 2023-10-22 12:35:04

Django is a powerful web framework for Python that makes it easy to build web applications quickly. In this guide, we will create a basic Django app from scratch. We will cover:</p>

<ul>
 	<li>Installing Django</li>
 	<li>Creating a project</li>
 	<li>Setting up the database</li>
 	<li>Creating an app</li>
 	<li>Defining models</li>
 	<li>Creating views</li>
 	<li>Setting up URLs</li>
 	<li>Templating with HTML</li>
 	<li>Serving static files</li>
 	<li>Working with forms</li>
 	<li>Admin interface</li>
 	<li>Deployment</li>
</ul>
By the end, you will have a simple web app running using Django's robust features. Let's get started!

You must understand Python and how to set it up; you can read some of these materials if you don't.
<ul>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/09/05/python-for-the-blinds-part-1/" target="_blank" rel="noopener noreferrer nofollow">Python for the blind</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/09/09/python-for-the-seniors-part-2/" target="_blank" rel="noopener noreferrer nofollow">Python for Seniors</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/10/06/build-a-website-blocker-app-with-python/" target="_blank" rel="noopener noreferrer nofollow">Build a website blocker with python</a></li>
</ul>
<h4>Install Django</h4>
Django can be installed easily using pip. Make sure you have Python 3 and pip installed first.

Open a terminal or command prompt and run:

<code>pip install Django</code>

This will install the latest version of Django.

You can verify Django has been installed successfully by running:

<code>python -m django --version</code>

This should print the installed Django version.
<h4>Create a Project</h4>
Once Django is installed, we can create our first project.

Go to the directory where you want to store your code and run:

<code>django-admin startproject myproject</code>

This will create a `myproject` folder with some auto-generated files and folders:
<ul>
 	<li><a href="http://manage.py" target="_blank" rel="noopener noreferrer nofollow">manage.py</a>: A command-line utility used to interact with the project.</li>
 	<li>myproject/settings.py: Settings and configuration for the Django project.</li>
 	<li>myproject/urls.py: The top-level URL routes for the Django project.</li>
 	<li>myproject/__init__.py: An empty file instructs Python to treat the myproject folder as a Python package.</li>
</ul>
<h4>Set Up Database</h4>
By default, Django uses SQLite which doesn't require any additional database setup. SQLite saves the database in a file in the project directory.

If you want to use another database like PostgreSQL or MySQL, install the appropriate database bindings and modify the DATABASES setting in myproject/settings.py.

For example, to use PostgreSQL:

<code>pip install psycopg2</code>

Then in <a href="http://settings.py" target="_blank" rel="noopener noreferrer nofollow">settings.py</a>:
```python
DATABASES = {

    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'password',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }

}
```
<h4>Create an App</h4>
Django projects are made up of different apps that each serve a distinct purpose.

To create an app called Pages:

<code>python </code><a href="http://manage.py" target="_blank" rel="noopener noreferrer nofollow"><code>manage.py</code></a><code> startapp pages</code>

This will create a pages folder within the project with its own <a href="http://models.py" target="_blank" rel="noopener noreferrer nofollow">models.py</a>, <a href="http://views.py" target="_blank" rel="noopener noreferrer nofollow">views.py</a>, etc.

Now register the app in myproject/settings.py under INSTALLED_APPS:
```python
INSTALLED_APPS = [

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'pages', # new
] 

```
The app is now ready to use.
<h4>Define Models</h4>
Models represent data for our application and are defined as classes in the app's <a href="http://models.py" target="_blank" rel="noopener noreferrer nofollow">models.py</a> file.

For our pages app, we can create a simple HomePage model:
```python
# pages/models.py


from django.db import models

class HomePage(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
```
<ul>
 	<li>models.Model makes this a Django model that will be saved in the database.</li>
 	<li>models.CharField is for small-to-large-sized text.</li>
 	<li>models.TextField is for large text content.</li>
</ul>
We'll also create a migration file to create the model in the database:

<code>python </code><a href="http://manage.py" target="_blank" rel="noopener noreferrer nofollow"><code>manage.py</code></a><code> makemigrations</code>

This will generate a migration file to create the HomePage table.

Then run the migrations using:

<code>python </code><a href="http://manage.py" target="_blank" rel="noopener noreferrer nofollow"><code>manage.py</code></a><code> migrate</code>

The HomePage model now exists in the database!
<h4>Create Views</h4>
Views are Python functions that handle requests and return responses.

In pages/views.py, we can create a simple view to render a template:
```python
# pages/views.py


from django.shortcuts import render
def home(request):
    return render(request, 'home.html', {'title':'My Home Page'})
```
This home view will look for a template called home.html and render it, passing the title as context.
<h4>Set Up URLs</h4>
URLs determine which view handles each request based on the request URL path.

In myproject/urls.py, add a path for our home view:
```python
from django.contrib import admin
from django.urls import path
from pages.views import home


urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home, name='home'), 
]
```
This maps requests to the site root URL '' to the home view.

We can add more paths later for additional views.
<h4>Templating with HTML</h4>
Django uses the templating language, Django Template Language (DTL), to generate dynamic HTML.

Templates go in a templates folder in each app. We can create templates/home.html:
```html
<!DOCTYPE HTML>

<HTML>
<head>
  <title>{{ title }} </title>
</head>
<body>
 <h1>{{ title }}</h1>;
  <p>{{ content }}</p>
</body>
</html>
```
Template tags `{{ title }} and {{ content }}` display values passed from the view.
<h4>Serve Static Files</h4>
Static files like CSS, JS, and images should go in a static folder in each app.

In <a href="http://settings.py" target="_blank" rel="noopener noreferrer nofollow">settings.py</a>, add:
```python
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
```
This tells Django where to look for static files.

In a template, load static files using:
```python
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
```
<h4>Work with Forms</h4>
Forms allow users to submit data to the app. Let's create a simple ContactForm.

In pages/forms.py:
```python
from django import forms

class ContactForm(forms.Form):
    name = forms.CharField()
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)
```
This creates a form with name, email, and message fields.

In <a href="http://views.py" target="_blank" rel="noopener noreferrer nofollow">views.py</a>:
```python
from .forms import ContactForm

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process form here
            return redirect('home')
    else:
        form = ContactForm()
    return render(request, 'contact.html', {'form': form})
```
This handles submitting the form and validating data.

The contact.html template can render the form:
```python
<form method="POST"&gt; {% csrf_token %}
  {{ form.as_p }}
  &lt;input type="submit" value="Submit"&gt;
/form>
```
Make sure to add the <strong>`{% csrf_token %}` </strong>to protect against attacks.

<h4>Admin Interface</h4>
Django provides a built-in admin interface to manage database content.

First, create a superuser:

<code>python </code><a href="http://manage.py" target="_blank" rel="noopener noreferrer nofollow"><code>manage.py</code></a><code> createsuperuser</code>

Enter your username, email, and password.

Now, in pages/admin.py, register the models:
```python
from django.contrib import admin
from .models import HomePage
admin.site.register(HomePage)
```
The model will now appear in the admin interface.

Start the dev server and go to /admin to log in and manage your models.
<h4>Deployment</h4>
To deploy online, configure <a href="http://settings.py" target="_blank" rel="noopener noreferrer nofollow">settings.py</a> for production use and set up WSGI using a web server like Nginx and Gunicorn.

Some key production settings:
<ul>
 	<li>DEBUG = False</li>
 	`<li>ALLOWED_HOSTS = ['<a href="http://www.mydomain.com" target="_blank" rel="noopener noreferrer nofollow">www.mydomain.com</a>']</li>`
 	<li>STATIC_ROOT = BASE_DIR / 'staticfiles'</li>
 	<li>SECURE_PROXY_SSL_HEADER</li>
</ul>
For faster deployment, use services like PythonAnywhere, Heroku, AWS Elastic Beanstalk to host Django projects.
<h4>Conclusion</h4>
That covers the basics of getting started with Django! We created a new project, made a simple model and views, displayed templates, handled forms, served static files, set up the admin, and prepared for deployment.

Django is very powerful, and this scratches the surface of what it can do. Some other areas to explore further include:
<ul>
 	<li>Custom user models and authentication</li>
 	<li>Class-based views for better code reuse</li>
 	<li>QuerySets for accessing and filtering data</li>
 	<li>Testing using the unit test module</li>
 	<li>Django REST Framework for APIs</li>
 	<li>Caching and performance optimization</li>
</ul>
The official Django documentation is fantastic and contains a wealth of information. Feel free to build on this project and turn it into a complete web app with additional features!

If you like my work and want to help me continue dropping content like this, buy me a <a class="attrlink" href="https://www.buymeacoffee.com/scofields1s" target="_blank" rel="noopener noreferrer nofollow">cup of coffee</a>.

If you find this post exciting, find more exciting posts on <a class="attrlink" href="http://blog.learnhub.africa/" target="_blank" rel="noopener noreferrer nofollow">Learnhub Blog</a>; we write everything tech from <a class="attrlink" href="https://blog.learnhub.africa/category/cloud-computing/" target="_blank" rel="noopener noreferrer nofollow">Cloud computing</a> to <a class="attrlink" href="https://blog.learnhub.africa/category/frontend/" target="_blank" rel="noopener noreferrer nofollow">Frontend Dev</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/security/" target="_blank" rel="noopener noreferrer nofollow">Cybersecurity</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/data-science/" target="_blank" rel="noopener noreferrer nofollow">AI</a>, and <a class="attrlink" href="https://blog.learnhub.africa/category/blockchain/" target="_blank" rel="noopener noreferrer nofollow">Blockchain</a>.
<h4>Resource</h4>
<ul>
 	<li><a class="attrlink" href="https://realpython.com/lessons/python-folium-get-started/" target="_blank" rel="noopener noreferrer nofollow">Getting started with Folium</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/05/26/20-essential-python-extensions-for-visual-studio-code/" target="_blank" rel="noopener noreferrer nofollow">20 Essential Python Extensions for Visual Studio Code</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/04/27/using-python-for-web-scraping-and-data-extraction/" target="_blank" rel="noopener noreferrer nofollow">Using Python for Web Scraping and Data Extraction</a></li>
 	<li><a class="attrlink" href="https://www.python.org/about/gettingstarted/" target="_blank" rel="noopener noreferrer nofollow">Getting Started with Python</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/10/04/creating-interactive-maps-with-folium-and-python/" target="_blank" rel="noopener noreferrer nofollow">Creating Interactive Maps with Folium and Python</a></li>
</ul>