Django

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. This tutorial will guide you through creating a basic Django application, covering the essentials from setup to deployment.

Step-by-Step Django Tutorial

1. Set Up Your Development Environment

  1. Install Python: Ensure Python 3.7 or later is installed on your system.
  2. Create a Project Directory:
    mkdir django_tutorial
    cd django_tutorial
    
  3. Set Up a Virtual Environment:
    python -m venv venv
    source venv/bin/activate   # On Windows, use `venv\Scripts\activate`
    
  4. Install Django:
    pip install django
    
  5. Verify the Installation:
    python -m django --version
    

2. Create a Django Project

  1. Start a New Project:
    django-admin startproject myproject
    cd myproject
    

    This command creates a myproject directory with the following structure:
    myproject/
        ├── manage.py
        └── myproject/
            ├── __init__.py
            ├── settings.py
            ├── urls.py
            ├── asgi.py
            └── wsgi.py
    
  2. Run the Development Server:
    python manage.py runserver
    

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

3. Create a Django App

  1. Create a New App:
    python manage.py startapp myapp
    

    The myapp directory will be created with the following structure:
    myapp/
        ├── __init__.py
        ├── admin.py
        ├── apps.py
        ├── models.py
        ├── tests.py
        └── views.py
    
  2. Register the App in settings.py: Add myapp to the INSTALLED_APPS list in myproject/settings.py:
    INSTALLED_APPS = [
        ...
        'myapp',
    ]
    

4. Creating Views and URLs

  1. Create a Simple View in myapp/views.py:
    from django.http import HttpResponse
    
    def home(request):
        return HttpResponse("Hello, Django!")
    
  2. Map the View to a URL in myapp/urls.py: Create a new file urls.py in the myapp directory:
    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('', views.home, name='home'),
    ]
    
  3. Include the App's URLs in the Project: Modify myproject/urls.py to include the myapp URLs:
    from django.contrib import admin
    from django.urls import include, path
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', include('myapp.urls')),
    ]
    
  4. Test the Application: Restart the server if it’s running:
    python manage.py runserver
    

    Visit http://127.0.0.1:8000/ to see "Hello, Django!".

5. Using Templates

  1. Create a Templates Directory: Inside myapp, create a templates folder and then a myapp folder inside it:
    myapp/
        ├── templates/
        │   └── myapp/
        │       └── home.html
    
  2. Add a Template File (home.html):
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Home</title>
    </head>
    <body>
        <h1>Welcome to Django!</h1>
        <p>{{ message }}</p>
    </body>
    </html>
    
  3. Update the View to Use the Template in myapp/views.py:
    from django.shortcuts import render
    
    def home(request):
        context = {'message': 'This is a Django app!'}
        return render(request, 'myapp/home.html', context)
    
  4. Test the Template: Refresh the browser at http://127.0.0.1:8000/ to see the new template rendering.

6. Working with Models and the Admin Interface

  1. Define a Model in myapp/models.py:
    from django.db import models
    
    class Post(models.Model):
        title = models.CharField(max_length=100)
        content = models.TextField()
    
        def __str__(self):
            return self.title
    
  2. Apply Migrations:
    python manage.py makemigrations
    python manage.py migrate
    
  3. Register the Model with the Admin Site in myapp/admin.py:
    from django.contrib import admin
    from .models import Post
    
    admin.site.register(Post)
    
  4. Create an Admin User:
    python manage.py createsuperuser
    

    Follow the prompts to create a superuser account.
  5. Access the Admin Interface: Start the server and go to http://127.0.0.1:8000/admin/. Log in with the superuser account to manage the Post model.

7. Handling Forms and User Input

  1. Create a Form: Create a forms.py file in the myapp directory:
    from django import forms
    from .models import Post
    
    class PostForm(forms.ModelForm):
        class Meta:
            model = Post
            fields = ['title', 'content']
    
  2. Update the View to Handle the Form in myapp/views.py:
    from django.shortcuts import redirect
    from .forms import PostForm
    
    def create_post(request):
        if request.method == 'POST':
            form = PostForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect('home')
        else:
            form = PostForm()
        return render(request, 'myapp/create_post.html', {'form': form})
    
  3. Create a Template for the Form (create_post.html):
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Create Post</title>
    </head>
    <body>
        <h1>Create a New Post</h1>
        <form method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Save</button>
        </form>
    </body>
    </html>
    
  4. Add a URL Pattern for the Form in myapp/urls.py:
    urlpatterns = [
        path('', views.home, name='home'),
        path('create/', views.create_post, name='create_post'),
    ]
    
  5. Test the Form: Visit http://127.0.0.1:8000/create/ to see the form and add new posts.

8. Static Files and CSS

  1. Create a Static Directory: Inside myapp, create a folder called static/myapp for your CSS files.
  2. Add a CSS File (style.css in static/myapp):
    body {
        font-family: Arial, sans-serif;
        background-color: #f8f9fa;
    }
    
  3. Link the CSS File in a Template: In home.html, add the following inside the <head> tag:
    <head>
        <link rel="stylesheet" href="{% static 'myapp/style.css' %}">
    </head>
    
  4. Update settings.py for Static Files: Ensure django.contrib.staticfiles is in INSTALLED_APPS and add:
    STATIC_URL = '/static/'
    
  5. Load Static Files: Ensure {% load static %} is at the top of your template file.

9. Deploying the Application

  1. Prepare for Deployment:
    • Remove debug=True from manage.py or set DEBUG = False in settings.py.
    • Use Django WhiteNoise to serve static files.
    • Configure your database for production (e.g., PostgreSQL).
  2. Deploy on a Hosting Platform:
    • Use services like Heroku, DigitalOcean, or AWS.
    • Follow the hosting platform’s specific Django deployment guides.

Summary

Django provides a comprehensive framework for building web applications quickly and efficiently. This tutorial covers the basics of setting up and working with Django, from creating a project to handling forms and deploying your application.