Комментарии (1)
🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
# Что такое context в Django views?
Context — это словарь, который передаёт данные из view (представления) в шаблон (template). Это мост между бэкенд-логикой и фронтенд-отображением.
Основная идея
View (Python) → Context (словарь) → Template (HTML)
from django.shortcuts import render
def hello_world(request):
# Создаём context — словарь с данными
context = {
'name': 'Alice',
'age': 25,
'city': 'Moscow'
}
# Передаём context в шаблон
return render(request, 'hello.html', context)
Использование в шаблоне
hello.html:
<h1>Привет, {{ name }}!</h1>
<p>Возраст: {{ age }}</p>
<p>Город: {{ city }}</p>
Результат в браузере:
Привет, Alice!
Возраст: 25
Город: Moscow
Основные компоненты Context
1. Простые значения
context = {
'title': 'My Page',
'count': 42,
'active': True,
}
2. Объекты из БД
from django.shortcuts import render, get_object_or_404
from .models import Article
def article_detail(request, article_id):
article = get_object_or_404(Article, id=article_id)
context = {
'article': article, # Передаём объект БД
}
return render(request, 'article.html', context)
article.html:
<h1>{{ article.title }}</h1>
<p>{{ article.content }}</p>
<p>Автор: {{ article.author.name }}</p>
3. Списки данных
def article_list(request):
articles = Article.objects.all()
context = {
'articles': articles,
}
return render(request, 'articles.html', context)
articles.html:
<ul>
{% for article in articles %}
<li>{{ article.title }} — {{ article.author }}</li>
{% endfor %}
</ul>
4. Сложные структуры
context = {
'user': {
'name': 'Alice',
'profile': {
'bio': 'Software Engineer',
'followers': 1000,
}
},
'metadata': {
'page_title': 'User Profile',
'created_at': timezone.now(),
}
}
Доступ в шаблоне:
<h1>{{ user.name }}</h1>
<p>{{ user.profile.bio }}</p>
<p>Подписчиков: {{ user.profile.followers }}</p>
Class-Based Views и Context
ListView
from django.views.generic import ListView
from .models import Article
class ArticleListView(ListView):
model = Article
template_name = 'articles.html'
context_object_name = 'articles' # Вместо 'object_list'
paginate_by = 10
Django автоматически добавляет:
articles— список статейis_paginated— есть ли пагинацияpage_obj— текущая страница
DetailView
from django.views.generic import DetailView
class ArticleDetailView(DetailView):
model = Article
template_name = 'article.html'
context_object_name = 'article'
def get_context_data(self, **kwargs):
"""Добавляем дополнительные данные в context"""
context = super().get_context_data(**kwargs)
context['related_articles'] = Article.objects.filter(
category=self.object.category
)[:5]
return context
Расширение Context через get_context_data()
from django.views.generic import TemplateView
class DashboardView(TemplateView):
template_name = 'dashboard.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# Добавляем данные
context['user'] = self.request.user
context['stats'] = self.get_stats()
context['notifications'] = self.request.user.notifications.all()
return context
def get_stats(self):
return {
'total_posts': Post.objects.count(),
'active_users': User.objects.filter(is_active=True).count(),
}
Фильтрация в Context
from django.db.models import Q, Count
def search(request):
query = request.GET.get('q', '')
context = {
'query': query,
'results': Article.objects.filter(
Q(title__icontains=query) |
Q(content__icontains=query)
),
'count': Article.objects.filter(
Q(title__icontains=query) |
Q(content__icontains=query)
).count(),
}
return render(request, 'search.html', context)
Производительность: Оптимизация Context
Плохо: N+1 проблема
def bad_view(request):
articles = Article.objects.all() # 1 запрос
# В шаблоне: {{ article.author.name }} → N запросов!
context = {'articles': articles}
return render(request, 'articles.html', context)
Хорошо: select_related / prefetch_related
def good_view(request):
# Загружаем авторов одним запросом
articles = Article.objects.select_related('author').all()
context = {'articles': articles}
return render(request, 'articles.html', context)
Передача Context напрямую
# Через render()
from django.shortcuts import render
return render(request, 'template.html', {'key': 'value'})
# Через JsonResponse (для API)
from django.http import JsonResponse
return JsonResponse({'key': 'value'})
# Через HttpResponse (редко)
from django.http import HttpResponse
return HttpResponse('<h1>Hello</h1>')
Процессоры Context (Context Processors)
Можно добавлять данные автоматически во все шаблоны:
# myapp/context_processors.py
def global_context(request):
return {
'site_name': 'My Site',
'current_year': 2024,
'user_is_premium': request.user.is_premium if request.user.is_authenticated else False,
}
# settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'OPTIONS': {
'context_processors': [
'myapp.context_processors.global_context',
],
},
},
]
Шпаргалка
# Function-based view
def my_view(request):
context = {'key': 'value'}
return render(request, 'template.html', context)
# Class-based view
class MyView(TemplateView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['key'] = 'value'
return context
# Доступ в шаблоне
{{ key }}
{{ object.attribute }}
{% for item in items %}...{% endfor %}
Вывод: Context — это просто словарь, который передаёт данные из view в template. Это основной механизм для отображения динамического контента в Django!