python-django-best-practices-cursorrules-prompt-fi — правило Cursor
Настраивает Cursor на архитектурные стандарты Django: разделение логики по MVT и оптимизацию ORM-запросов.
.cursor/rules/python-django-best-practices-cursorrules-prompt-fi.mdcЧто делает python-django-best-practices-cursorrules-prompt-fi
Правило ориентирует ИИ-ассистента на разделение ответственности по схеме MVT. Логику предписано держать в моделях и формах, оставляя представления компактными. Для сложных сценариев задаются классы CBV, а для базовых действий — функции FBV. Обращения к базе данных идут через Django ORM: правило прямо требует задействовать select_related и prefetch_related, чтобы избежать медленных запросов.
Стек опирается на Django REST Framework для JSON API и Celery с Redis для асинхронных задач. Для продакшена инструкция выделяет PostgreSQL и MySQL. Тестирование строится на unittest или pytest-django.
Так как параметр alwaysApply отключён, Cursor не станет подмешивать эти указания в каждый диалог подряд.
Какие задачи решает
- удерживать бизнес-логику в моделях и формах без перегрузки представлений
- оптимизировать выборки к базе данных через select_related и prefetch_related
- настроить фоновые задачи через Celery и Redis
- структурировать проект на независимые приложения Django
Примеры запросов агенту
- Напиши класс представления на CBV с выборкой связанных данных через select_related
- Вынеси долгую операцию генерации отчёта в фоновую задачу Celery
- Добавь валидацию входящих данных через форму Django и настрой обработку ошибок
Как установить python-django-best-practices-cursorrules-prompt-fi
Вручную: положить файлы
.cursor/rules/python-django-best-practices-cursorrules-prompt-fi.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.claude/rules/python-django-best-practices-cursorrules-prompt-fi.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/python-django-best-practices-cursorrules-prompt-fi.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/python-django-best-practices-cursorrules-prompt-fi.mdВручную: положить файлы
.clinerules/python-django-best-practices-cursorrules-prompt-fi.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Вопросы о python-django-best-practices-cursorrules-prompt-fi
Как установить python-django-best-practices-cursorrules-prompt-fi в Cursor?
Создайте файл .cursor/rules/python-django-best-practices-cursorrules-prompt-fi.mdc в корне проекта и сохраните в него текст правила.
Что делает python-django-best-practices-cursorrules-prompt-fi?
Задаёт правила генерации кода Django: требует соблюдать шаблон MVT, использовать встроенные механизмы авторизации и оптимизировать обращения к ORM.
Какие базы данных и библиотеки рекомендует это правило?
В инструкции упомянуты Django REST Framework, Celery, Redis, а в качестве баз данных для продакшена указаны PostgreSQL и MySQL.
Исходный текст
python-django-best-practices-cursorrules-prompt-fi.mdc · CC0-1.0
--- description: "Cursor rules for Python Django development with best practices." globs: **/* alwaysApply: false --- You are an expert in Python, Django, and scalable web application development. Key Principles - Write clear, technical responses with precise Django examples. - Use Django's built-in features and tools wherever possible to leverage its full capabilities. - Prioritize readability and maintainability; follow Django's coding style guide (PEP 8 compliance). - Use descriptive variable and function names; adhere to naming conventions (e.g., lowercase with underscores for functions and variables). - Structure your project in a modular way using Django apps to promote reusability and separation of concerns. Django/Python - Use Django’s class-based views (CBVs) for more complex views; prefer function-based views (FBVs) for simpler logic. - Leverage Django’s ORM for database interactions; avoid raw SQL queries unless necessary for performance. - Use Django’s built-in user model and authentication framework for user management. - Utilize Django's form and model form classes for form handling and validation. - Follow the MVT (Model-View-Template) pattern strictly for clear separation of concerns. - Use middleware judiciously to handle cross-cutting concerns like authentication, logging, and caching. Error Handling and Validation - Implement error handling at the view level and use Django's built-in error handling mechanisms. - Use Django's validation framework to validate form and model data. - Prefer try-except blocks for handling exceptions in business logic and views. - Customize error pages (e.g., 404, 500) to improve user experience and provide helpful information. - Use Django signals to decouple error handling and logging from core business logic. Dependencies - Django - Django REST Framework (for API development) - Celery (for background tasks) - Redis (for caching and task queues) - PostgreSQL or MySQL (preferred databases for production) Django-Specific Guidelines - Use Django templates for rendering HTML and DRF serializers for JSON responses. - Keep business logic in models and forms; keep views light and focused on request handling. - Use Django's URL dispatcher (urls.py) to define clear and RESTful URL patterns. - Apply Django's security best practices (e.g., CSRF protection, SQL injection protection, XSS prevention). - Use Django’s built-in tools for testing (unittest and pytest-django) to ensure code quality and reliability. - Leverage Django’s caching framework to optimize performance for frequently accessed data. - Use Django’s middleware for common tasks such as authentication, logging, and security. Performance Optimization - Optimize query performance using Django ORM's select_related and prefetch_related for related object fetching. - Use Django’s cache framework with backend support (e.g., Redis or Memcached) to reduce database load. - Implement database indexing and query optimization techniques for better performance. - Use asynchronous views and background tasks (via Celery) for I/O-bound or long-running operations. - Optimize static file handling with Django’s static file management system (e.g., WhiteNoise or CDN integration). Key Conventions 1. Follow Django's "Convention Over Configuration" principle for reducing boilerplate code. 2. Prioritize security and performance optimization in every stage of development. 3. Maintain a clear and logical project structure to enhance readability and maintainability. Refer to Django documentation for best practices in views, models, forms, and security considerations.
© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules