Introduction to Django: A Comprehensive Beginner's Guide to Backend Web Development

Olatunde Emmanuel - Jul 25 - - Dev Community

Introduction to Django

Django is a high-level web application framework that develops web applications using Python. It promotes rapid development and clean pragmatic design.

Key Features of Django

  • Professional Design: Designed by seasoned developers to enhance the web creation process.
  • Efficiency: Reduces repetitive tasks so you don't have to recreate the same application from scratch.

Setting Up Django

First, you need to install Python on your machine before using Django. After acquiring Python, you can set up Django using pip:

pip install django
Enter fullscreen mode Exit fullscreen mode

Creating a Django Project

A Django project is a set of settings for one Django instance. It consists of database configurations, Django-specific options, and application-specific settings.

Start a new project:

django-admin startproject myproject
cd myproject
Enter fullscreen mode Exit fullscreen mode

Run the development server:

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Open your web browser and go to http://127.0.0.1:8000/ to see the default Django welcome page.

Creating a Django App

An application in Django carries out a particular task. This could be a blogging platform, a database of public records, or a polling application.

Start a new app:

python manage.py startapp myapp
Enter fullscreen mode Exit fullscreen mode

Add the app to your project: In myproject/settings.py, add 'myapp' to the INSTALLED_APPS list:

INSTALLED_APPS = [
    # other installed apps
    'myapp',
]
Enter fullscreen mode Exit fullscreen mode

How the folder looks after creation

Creating a Simple View

A view function takes a web request and returns a web response. This response can be HTML content, a redirect, a 404 error, an XML document, or an image.

Create a view in myapp/views.py:

from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello Django!")
Enter fullscreen mode Exit fullscreen mode

Create a Python file urls.py in myapp

Map the view to a URL in myapp/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home')
]
Enter fullscreen mode Exit fullscreen mode

Include the app's URLs in the project’s URLs in myproject/urls.py:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]
Enter fullscreen mode Exit fullscreen mode

Working with Templates

The template system offered by Django is straightforward and adaptable. The templates are in a directory called templates within the application folder.

Create a templates directory inside myapp and add an index.html file:

<!DOCTYPE html>
<html>
<head>
    <title>My Django App</title>
</head>
<body>
    <h1>Hello Django!</h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Modify settings.py to include the templates directory:

   import os
   BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

   TEMPLATES = [
       {
           'BACKEND': 'django.template.backends.django.DjangoTemplates',
           'DIRS': [os.path.join(BASE_DIR, 'myapp', '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',
               ],
           },
       },
   ]
Enter fullscreen mode Exit fullscreen mode

Update the view to use the template in myapp/views.py:

from django.shortcuts import render

def home(request):
    return render(request, 'index.html')
Enter fullscreen mode Exit fullscreen mode

Models and Databases

Models are the single definitive source of information about your data. They contain the essential fields and behaviors of the data you’re storing.

Define a model in myapp/models.py:

from django.db import models

class Weather(models.Model):
    city = models.CharField(max_length=100)
    temperature = models.FloatField()
    description = models.CharField(max_length=100)
Enter fullscreen mode Exit fullscreen mode

Create the database tables:

python manage.py makemigrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Django Admin

Django comes with a built-in admin interface that is highly customizable.

Create an admin user:

python manage.py createsuperuser
Enter fullscreen mode Exit fullscreen mode

Register the model in myapp/admin.py:

from django.contrib import admin
from .models import Weather

admin.site.register(Weather)
Enter fullscreen mode Exit fullscreen mode

Access the admin interface: Open your web browser and go to http://127.0.0.1:8000/admin/.

Possible Errors and How to Resolve Them

When working with Django, you may encounter various errors. Here are some common ones and their solutions:

  1. Command Not Found

    • Error: django-admin: command not found
    • Solution: Ensure Django is installed using pip install django.
  2. Server Not Running

    • Error: That port is already in use.
    • Solution: Stop other processes using the port or change the port:
     python manage.py runserver 8080
    
  3. Template Not Found

    • Error: TemplateDoesNotExist at /
    • Solution: Ensure the template path is correct and included in TEMPLATES settings in settings.py.
  4. Database Migration Errors

    • Error: django.db.utils.OperationalError: no such table
    • Solution: Run migrations:
     python manage.py makemigrations
     python manage.py migrate
    
  5. Static Files Not Loading

    • Solution: Ensure STATIC_URL and STATICFILES_DIRS are properly configured in settings.py.
  6. Form Data Not Valid

    • Solution: Check form field names in the template and ensure they match the form definition in forms.py.
  7. 404 Error for URL

    • Solution: Ensure URL patterns are correctly defined and included in the project's urls.py.
  8. Admin Interface Errors

    • Solution: Ensure models are registered in admin.py and the admin user is created.

These common issues and their solutions should help you troubleshoot effectively while working with Django.

For more advanced features, in-depth explanations, detailed error messages, follow up this series and always check the Django documentation and community forums.

. . . . . . . . .