How to get started with Django

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Getting Started with Django: A Step-by-Step Guide for Beginners

If you've mastered the basics of Python and are planning to try your hand at web application development, Django is an excellent choice. This popular and powerful Python web framework allows you to quickly create robust, secure, and scalable web applications. With it, you can develop anything from a simple blog to a complex corporate portal.

What is Django and Its Benefits

Django is a high-level web framework written in Python. The main philosophy of the framework is "Don't Repeat Yourself" (DRY). This principle allows you to write clean, logical, and reusable code.

Key Benefits of Django

  • Simplicity and high speed of web application development
  • Built-in security features to protect against major threats
  • Powerful templating engine for working with HTML markup
  • Ready-made administrative panel without additional configuration
  • ORM (Object-Relational Mapping) support for convenient work with databases
  • Active developer community and a large number of free libraries
  • Detailed documentation and many training materials
  • Scalability and performance for projects of any size

Installing Django and Preparing the Development Environment

Checking and Installing Python

Make sure you have Python version 3.8 or higher installed on your computer. You can check the version with the command:

python --version

If Python is not installed, download it from the official website python.org and follow the installation instructions for your operating system.

Creating a Virtual Environment

To isolate the project and avoid conflicts between different projects, it is recommended to work in a virtual environment:

python -m venv venv
source venv/bin/activate  # For Linux/MacOS
venv\Scripts\activate     # For Windows

The virtual environment helps manage project dependencies and prevents conflicts between different versions of libraries.

Installing the Django Framework

After activating the virtual environment, install Django:

pip install django

Check the success of the installation and the Django version:

django-admin --version

Creating Your First Django Project

Initializing a New Project

Create a new Django project using the command:

django-admin startproject mysite
cd mysite

After executing the command, the following file structure will be created:

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

Where:

  • manage.py - utility for managing the project
  • settings.py - project settings file
  • urls.py - URL routing configuration
  • wsgi.py and asgi.py - files for deployment on the server

Running the Built-in Development Server

To test the project, use the built-in development server:

python manage.py runserver

Open your browser and go to http://127.0.0.1:8000/. You will see the Django welcome page, which confirms the correctness of the installation and configuration.

Creating Your First Application

Django follows the architectural principle "Project contains applications". Each application is responsible for a specific functionality. Let's create an application for a blog:

python manage.py startapp blog

As a result, a blog folder will appear with the following structure:

blog/
    __init__.py
    admin.py
    apps.py
    models.py
    tests.py
    views.py
    migrations/

Don't forget to add the created application to the INSTALLED_APPS list in the settings.py file:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
]

Working with Data Models

Creating a Model in models.py

Models in Django define the data structure and logic for working with the database. Let's create a simple model for a blog post:

from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=200, verbose_name="Заголовок")
    slug = models.SlugField(max_length=200, unique=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Автор")
    content = models.TextField(verbose_name="Содержание")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="Дата создания")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="Дата обновления")
    status = models.CharField(max_length=10, choices=[
        ('draft', 'Черновик'),
        ('published', 'Опубликовано')
    ], default='draft')

    class Meta:
        ordering = ['-created_at']
        verbose_name = "Пост"
        verbose_name_plural = "Посты"

    def __str__(self):
        return self.title

Configuring the Administrative Panel

The Django administrative panel allows you to easily manage data. Register the model in the admin.py file:

from django.contrib import admin
from .models import Post

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ['title', 'author', 'status', 'created_at']
    list_filter = ['status', 'created_at', 'author']
    search_fields = ['title', 'content']
    prepopulated_fields = {'slug': ('title',)}
    date_hierarchy = 'created_at'
    ordering = ['status', '-created_at']

Migrations and Working with the Database

Creating and Applying Migrations

Migrations in Django track changes in models and apply them to the database:

python manage.py makemigrations
python manage.py migrate

The makemigrations command creates migration files based on changes in the models, and migrate applies these changes to the database.

Creating a Superuser

To access the administrative panel, create an administrator account:

python manage.py createsuperuser

Enter a username, email, and password. After that, you will be able to log in to the administrative panel at http://127.0.0.1:8000/admin/.

Creating Views and Routing

Basic Views in views.py

Views process HTTP requests and return HTTP responses. Let's create a few views:

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Post

def home(request):
    posts = Post.objects.filter(status='published').order_by('-created_at')[:5]
    return render(request, 'blog/home.html', {'posts': posts})

def post_detail(request, slug):
    post = get_object_or_404(Post, slug=slug, status='published')
    return render(request, 'blog/post_detail.html', {'post': post})

def post_list(request):
    posts = Post.objects.filter(status='published')
    return render(request, 'blog/post_list.html', {'posts': posts})

Configuring URL Routes

Create a urls.py file in the blog application directory:

from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [
    path('', views.home, name='home'),
    path('posts/', views.post_list, name='post_list'),
    path('post/<slug:slug>/', views.post_detail, name='post_detail'),
]

Connect the application routes in the main mysite/urls.py file:

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

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

Working with Templates

Creating a Template Structure

Create a templates/blog/ folder inside the application and add a basic base.html template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}My Blog{% endblock %}</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'blog/css/style.css' %}">
</head>
<body>
    <header>
        <nav>
            <a href="{% url 'blog:home' %}">Home</a>
            <a href="{% url 'blog:post_list' %}">All Posts</a>
        </nav>
    </header>

    <main>
        {% block content %}
        {% endblock %}
    </main>

    <footer>
        <p>&copy; 2024 My Blog. All rights reserved.</p>
    </footer>
</body>
</html>

Home Page Template

Create home.html:

{% extends 'blog/base.html' %}

{% block title %}Home - My Blog{% endblock %}

{% block content %}
<h1>Welcome to my blog!</h1>
<h2>Latest Posts</h2>

{% if posts %}
    {% for post in posts %}
    <article>
        <h3><a href="{% url 'blog:post_detail' post.slug %}">{{ post.title }}</a></h3>
        <p class="meta">Author: {{ post.author.username }} | Date: {{ post.created_at|date:"d.m.Y" }}</p>
        <p>{{ post.content|truncatewords:30 }}</p>
    </article>
    {% endfor %}
{% else %}
    <p>No published posts yet.</p>
{% endif %}
{% endblock %}

Static Files and Styling

Configuring Static Files

In the settings.py file, make sure that the paths for static files are configured:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR / "static",
]
STATIC_ROOT = BASE_DIR / "staticfiles"

Creating CSS Styles

Create a folder static/blog/css/ and a file style.css:

body {
    font-family: Arial, sans-serif;
    line-height: 1.6;
    margin: 0;
    padding: 0;
    background-color: #f4f4f4;
}

header {
    background-color: #333;
    color: white;
    padding: 1rem;
}

nav a {
    color: white;
    text-decoration: none;
    margin-right: 1rem;
}

main {
    max-width: 800px;
    margin: 2rem auto;
    padding: 0 1rem;
    background-color: white;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

article {
    border-bottom: 1px solid #eee;
    padding: 1rem 0;
}

.meta {
    color: #666;
    font-size: 0.9rem;
}

Additional Django Features

Working with Forms

Django provides a powerful mechanism for working with HTML forms. Create a forms.py file:

from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'slug', 'content', 'status']
        widgets = {
            'content': forms.Textarea(attrs={'rows': 10}),
            'title': forms.TextInput(attrs={'class': 'form-control'}),
        }

Authorization System

Django includes a ready-made authorization system. Add views for login and registration:

from django.contrib.auth import login
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import redirect

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('blog:home')
    else:
        form = UserCreationForm()
    return render(request, 'registration/register.html', {'form': form})

Directions for Further Study

After mastering the basic concepts of Django, it is recommended to study the following topics:

  • Advanced work with forms and data validation
  • Authorization system and user access rights
  • Django REST Framework for creating APIs
  • Caching and optimizing application performance
  • Testing Django applications
  • Deployment on servers (Heroku, DigitalOcean, AWS)
  • Integration with external services and APIs
  • Working with Django signals
  • Creating your own middleware
  • Internationalization and localization

Useful Resources for Learning

  • Official Django documentation
  • Django Girls Tutorial for beginners
  • Real Python Django courses
  • MDN Web Docs on web development
  • Django community on GitHub
  • Forums and chats of Django developers

Now you have a complete understanding of how to start working with Django. This powerful framework allows you to quickly develop reliable web applications, using built-in security features and a convenient administrative panel. Study the documentation, experiment with the code, and soon you will be able to create complex projects from scratch.

News