0%
Web Development with Django

Web Development with Django

How to build robust web applications with the Django framework.

I

InSkillCoach

· min

Web Development with Django

Django is a high-level Python web framework that encourages rapid, clean development. With its “batteries included” philosophy, Django provides everything you need to build robust, maintainable web applications.

Why Choose Django?

Django offers many advantages for web development:

  • Fast to develop with: Django follows the DRY (Don’t Repeat Yourself) principle and automates many tasks
  • Secure by default: Protection against common web vulnerabilities (XSS, CSRF, SQL injection…)
  • Scalable: Used by high-traffic sites such as Instagram, Pinterest, and Disqus
  • Batteries included: Built-in ORM, automatic admin, template system, authentication…
  • Active community: Excellent documentation and plenty of resources available

Installation and Setup

To get started with Django, install it via pip:

# Créer un environnement virtuel
python -m venv venv
source venv/bin/activate  # Sur Windows: venv\Scripts\activate

# Installer Django
pip install django

# Créer un nouveau projet
django-admin startproject monsite

# Naviguer vers le projet
cd monsite

# Créer une application
python manage.py startapp blog

Structure of a Django Project

A typical Django project is organized as follows:

monsite/
    manage.py
    monsite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py
    blog/
        __init__.py
        admin.py
        apps.py
        models.py
        tests.py
        views.py
        urls.py
        migrations/
        templates/
            blog/
                base.html
                index.html
                detail.html
        static/
            blog/
                css/
                js/
                images/

Models: Defining Your Data

Django models define the structure of your data:

# blog/models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Category(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(unique=True)
    
    def __str__(self):
        return self.name
    
    class Meta:
        verbose_name_plural = "categories"

class Post(models.Model):
    STATUS_CHOICES = (
        ('draft', 'Brouillon'),
        ('published', 'Publié'),
    )
    
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique_for_date='publish')
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
    body = models.TextField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='posts')
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
    
    def __str__(self):
        return self.title
    
    class Meta:
        ordering = ('-publish',)

After defining your models, create and apply the migrations:

python manage.py makemigrations
python manage.py migrate

Views: Your Application’s Logic

Views handle requests and return responses:

# blog/views.py
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from .models import Post, Category

def post_list(request, category_slug=None):
    posts = Post.objects.filter(status='published')
    category = None
    
    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        posts = posts.filter(category=category)
    
    paginator = Paginator(posts, 10)  # 10 posts per page
    page = request.GET.get('page')
    posts = paginator.get_page(page)
    
    return render(request, 'blog/post_list.html', {
        'posts': posts,
        'category': category
    })

def post_detail(request, year, month, day, post_slug):
    post = get_object_or_404(
        Post,
        slug=post_slug,
        status='published',
        publish__year=year,
        publish__month=month,
        publish__day=day
    )
    
    return render(request, 'blog/post_detail.html', {'post': post})

URLs: Request Routing

Configure URLs to direct requests to the appropriate views:

# blog/urls.py
from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('category/<slug:category_slug>/', views.post_list, name='post_list_by_category'),
    path('<int:year>/<int:month>/<int:day>/<slug:post_slug>/', views.post_detail, name='post_detail'),
]

# monsite/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls', namespace='blog')),
]

Templates: The User Interface

Templates define how data is presented:

<!-- blog/templates/blog/base.html -->
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}Mon Blog{% endblock %}</title>
    <link rel="stylesheet" href="{% static 'blog/css/style.css' %}">
</head>
<body>
    <header>
        <h1>Mon Blog</h1>
        <nav>
            <ul>
                <li><a href="{% url 'blog:post_list' %}">Accueil</a></li>
                {% for cat in categories %}
                <li><a href="{% url 'blog:post_list_by_category' cat.slug %}">{{ cat.name }}</a></li>
                {% endfor %}
            </ul>
        </nav>
    </header>
    
    <main>
        {% block content %}
        {% endblock %}
    </main>
    
    <footer>
        <p>&copy; {% now "Y" %} Mon Blog</p>
    </footer>
</body>
</html>

<!-- blog/templates/blog/post_list.html -->
{% extends "blog/base.html" %}

{% block title %}
    {% if category %}{{ category.name }}{% else %}Articles{% endif %}
{% endblock %}

{% block content %}
    <h2>
        {% if category %}
            Articles dans la catégorie "{{ category.name }}"
        {% else %}
            Tous les articles
        {% endif %}
    </h2>
    
    {% for post in posts %}
        <article>
            <h3><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h3>
            <p class="date">Publié le {{ post.publish }} par {{ post.author }}</p>
            <p>{{ post.body|truncatewords:30|linebreaks }}</p>
        </article>
    {% empty %}
        <p>Aucun article disponible.</p>
    {% endfor %}
    
    {% include "pagination.html" with page=posts %}
{% endblock %}

Django Administration

Django provides a ready-to-use admin interface:

# blog/admin.py
from django.contrib import admin
from .models import Category, Post

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'slug')
    prepopulated_fields = {'slug': ('name',)}

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'slug', 'author', 'publish', 'status')
    list_filter = ('status', 'created', 'publish', 'author')
    search_fields = ('title', 'body')
    prepopulated_fields = {'slug': ('title',)}
    raw_id_fields = ('author',)
    date_hierarchy = 'publish'
    ordering = ('status', 'publish')

Running the Development Server

To test your application:

python manage.py runserver

Go to http://127.0.0.1:8000/ in your browser.

Advanced Features

Django offers many advanced features:

  • Authentication: A complete user management system
  • Forms: Form creation, validation, and processing
  • Testing: Built-in testing framework
  • Internationalization: Multilingual support
  • Caching: Multiple levels of caching
  • Security: Protection against common attacks

Deployment

To deploy a Django application to production:

  1. Configure production settings in settings.py
  2. Collect static files: python manage.py collectstatic
  3. Choose a WSGI server such as Gunicorn or uWSGI
  4. Set up a web server such as Nginx or Apache
  5. Use a robust database such as PostgreSQL

Conclusion

Django is a powerful framework that lets you quickly build complex, secure web applications. Its “batteries included” philosophy and well-organized structure make it an excellent choice for Python developers who want to create robust, maintainable websites.

Whether you’re building a simple blog, an e-commerce site, or a complex web application, Django gives you the tools you need to make your project a success.

InSkillCoach

About InSkillCoach

Training and technology expert

Coach specializing in advanced technologies and AI, backed by GNeurone Inc.

Certifications:

  • AWS Certified Solutions Architect – Professional
  • Google Cloud certifications
  • Microsoft Certified: DevOps Engineer Expert
  • Certified Kubernetes Administrator (CKA)
  • CompTIA Security+
1.9k
249

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!