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:
- Installing Django
- Creating a project
- Setting up the database
- Creating an app
- Defining models
- Creating views
- Setting up URLs
- Templating with HTML
- Serving static files
- Working with forms
- Admin interface
- Deployment
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.
Install Django
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:
pip install Django
This will install the latest version of Django.
You can verify Django has been installed successfully by running:
python -m django --version
This should print the installed Django version.
Create a Project
Once Django is installed, we can create our first project.
Go to the directory where you want to store your code and run:
django-admin startproject myproject
This will create a myproject
folder with some auto-generated files and folders:
- manage.py: A command-line utility used to interact with the project.
- myproject/settings.py: Settings and configuration for the Django project.
- myproject/urls.py: The top-level URL routes for the Django project.
- myproject/__init__.py: An empty file instructs Python to treat the myproject folder as a Python package.
Set Up Database
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:
pip install psycopg2
Then in settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'password',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
Create an App
Django projects are made up of different apps that each serve a distinct purpose.
To create an app called Pages:
python
manage.py
startapp pages
This will create a pages folder within the project with its own models.py, views.py, etc.
Now register the app in myproject/settings.py under INSTALLED_APPS:
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.
Define Models
Models represent data for our application and are defined as classes in the app's models.py file.
For our pages app, we can create a simple HomePage model:
# pages/models.py
from django.db import models
class HomePage(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
- models.Model makes this a Django model that will be saved in the database.
- models.CharField is for small-to-large-sized text.
- models.TextField is for large text content.
We'll also create a migration file to create the model in the database:
python
manage.py
makemigrations
This will generate a migration file to create the HomePage table.
Then run the migrations using:
python
manage.py
migrate
The HomePage model now exists in the database!
Create Views
Views are Python functions that handle requests and return responses.
In pages/views.py, we can create a simple view to render a template:
# 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.
Set Up URLs
URLs determine which view handles each request based on the request URL path.
In myproject/urls.py, add a path for our home view:
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.
Templating with HTML
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:
<!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.
Serve Static Files
Static files like CSS, JS, and images should go in a static folder in each app.
In settings.py, add:
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
This tells Django where to look for static files.
In a template, load static files using:
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
Work with Forms
Forms allow users to submit data to the app. Let's create a simple ContactForm.
In pages/forms.py:
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 views.py:
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:
<form method="POST"> {% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
/form>
Make sure to add the {% csrf_token %}
to protect against attacks.
Admin Interface
Django provides a built-in admin interface to manage database content.
First, create a superuser:
python
manage.py
createsuperuser
Enter your username, email, and password.
Now, in pages/admin.py, register the models:
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.
Deployment
To deploy online, configure settings.py for production use and set up WSGI using a web server like Nginx and Gunicorn.
Some key production settings:
- DEBUG = False `
- ALLOWED_HOSTS = ['www.mydomain.com'] `
- STATIC_ROOT = BASE_DIR / 'staticfiles'
- SECURE_PROXY_SSL_HEADER
For faster deployment, use services like PythonAnywhere, Heroku, AWS Elastic Beanstalk to host Django projects.
Conclusion
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:
- Custom user models and authentication
- Class-based views for better code reuse
- QuerySets for accessing and filtering data
- Testing using the unit test module
- Django REST Framework for APIs
- Caching and performance optimization
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 cup of coffee.
If you find this post exciting, find more exciting posts on Learnhub Blog; we write everything tech from Cloud computing to Frontend Dev, Cybersecurity, AI, and Blockchain.
Top comments (0)