Logo Django

Django

Cộng đồng
wsvincent
django

Django best practices and conventions. Use when creating, refactoring, or reviewing Django projects, apps, models, views, templates, forms, admin, tests, or settings. Keeps Django code secure, idiomatic, and up to date with the latest features and patterns. Triggers on starting a Django project or app, writing models/migrations/querysets, class-based or function-based views, forms and validation, templates, the admin, tests, async views and background tasks, deployment and security settings, N+1 and slow-query debugging, and Django version upgrades.

Tổng quan

Nhà phát hànhwsvincent
Kho mãdjango-skills
Tên kỹ năngdjango
Sao
40
Bản fork
3
Tệp đi kèm
9
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 9 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được wsvincent công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Django trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/wsvincent/django-skills/tree/main
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wsvincent/django-skills.git \
  .claude/skills/django
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Django trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Django ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Django không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Django

An unofficial skill for writing Django code with best practices, based on the official Django documentation and community conventions, keeping up to date with new versions and features.

Target Django 6.x and Python 3.12+ for new projects. Django 5.2 is the current LTS; do not write code for versions older than the LTS unless the project requires it. Features new in Django 6.0 and 6.1 are marked below.

Quick Reference

Use django-admin and manage.py

Create a new project and app:

bash
django-admin startproject config .
python manage.py startapp accounts

Run the development server, create and apply migrations, and run tests:

bash
python manage.py runserver
python manage.py makemigrations
python manage.py migrate
python manage.py test

Before deploying, always run the deployment checklist:

bash
python manage.py check --deploy

Settings

Never hardcode secrets. Read SECRET_KEY, database credentials, and API keys from environment variables, and never commit them:

python
import os

SECRET_KEY = os.environ["SECRET_KEY"]
DEBUG = os.environ.get("DEBUG", "") == "True"

instead of:

python
# DO NOT DO THIS
SECRET_KEY = "django-insecure-hardcoded-value"
DEBUG = True  # left on in production

DEBUG must be False in production, with ALLOWED_HOSTS set explicitly. See the deployment reference for settings layout, production settings, security headers, CSP, static files, caching, and email configuration.

Always Start With a Custom User Model

For any new project, define a custom user model before running the first migration, even if the default behavior is all that's needed. Changing the user model mid-project is painful; the official docs strongly recommend this.

python
# accounts/models.py
from django.contrib.auth.models import AbstractUser


class CustomUser(AbstractUser):
    pass
python
# settings.py
AUTH_USER_MODEL = "accounts.CustomUser"

Reference the user model via settings.AUTH_USER_MODEL in ForeignKey declarations and get_user_model() everywhere else:

python
from django.conf import settings
from django.db import models


class Article(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

instead of:

python
# DO NOT DO THIS
from django.contrib.auth.models import User


class Article(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)

Models and QuerySets

See the ORM reference for detailed patterns: model conventions, choices enums, constraints and indexes, on_delete options (including the database-level DB_CASCADE family in 6.1), custom managers and querysets, queryset performance, fetch modes, transactions, and migrations.

The essentials:

  • Give every model a __str__ method and use TextChoices/IntegerChoices for choices.
  • Avoid N+1 queries with select_related("field") and prefetch_related("field") — always pass explicit field names. On Django 6.1+, QuerySet.fetch_mode(models.FETCH_PEERS) solves most N+1 problems without maintaining a field list.
  • Use the database, not Python: exists(), count(), bulk_create(), F() expressions.
  • Put business logic on models, managers, or a service layer — not in views or templates.
  • Never interpolate values into raw SQL — pass parameters.

URLs

Use path() with converters, name every URL pattern, and namespace apps with app_name. Never hardcode URLs; use reverse(), reverse_lazy(), and the {% url %} template tag:

python
# articles/urls.py
from django.urls import path

from .views import ArticleDetailView, ArticleListView

app_name = "articles"
urlpatterns = [
    path("", ArticleListView.as_view(), name="list"),
    path("<int:pk>/", ArticleDetailView.as_view(), name="detail"),
]
html
<a href="{% url 'articles:detail' article.pk %}">{{ article.title }}</a>

instead of:

html
<!-- DO NOT DO THIS -->
<a href="/articles/{{ article.pk }}/">{{ article.title }}</a>

Views

Use generic class-based views for standard CRUD patterns; function-based views are fine for one-off logic. Use get_object_or_404() instead of catching DoesNotExist manually, and LoginRequiredMixin / @login_required for authentication:

python
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import DetailView, ListView

from .models import Article


class ArticleListView(ListView):
    model = Article
    context_object_name = "articles"

    def get_queryset(self):
        return Article.objects.select_related("author")


class ArticleDetailView(LoginRequiredMixin, DetailView):
    model = Article

instead of:

python
# DO NOT DO THIS
def article_detail(request, pk):
    try:
        article = Article.objects.get(pk=pk)
    except Article.DoesNotExist:
        return HttpResponse(status=404)

Redirect after a successful POST. Never mutate data in a GET request. To preserve the HTTP method and body through a redirect, use RedirectView.preserve_request = True (Django 6.1+), which issues 307/308 instead of 302/301.

See the views and forms reference for URL patterns, view customization hooks, permissions, pagination, and the messages framework. Write async views only when the code inside genuinely awaits; see the async reference.

Forms

Always validate user input through Django forms. Use ModelForm for model-backed input, list fields explicitly, and access data via cleaned_data:

python
from django import forms

from .models import Article


class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = ["title", "status"]

instead of:

python
# DO NOT DO THIS
fields = "__all__"  # can silently expose new sensitive fields

# DO NOT DO THIS — bypasses all validation
Article.objects.create(title=request.POST["title"])

See the views and forms reference for validation hooks, formsets, and file uploads.

Templates

Use template inheritance with a base template and {% block %} tags. Always include {% csrf_token %} in POST forms. Rely on autoescaping — never pass user-generated content through |safe or mark_safe().

Template Partials

Use {% partialdef %} and {% partial %} (Django 6.0+) to define and reuse named fragments within a template file, instead of splitting tiny components into separate files:

html
{% partialdef article-card %}
  <article>
    <h2>{{ article.title }}</h2>
  </article>
{% endpartialdef %}

{% for article in articles %}
  {% partial article-card %}
{% endfor %}

Partials can be rendered directly from views with the template_name#partial_name syntax — useful for htmx-style partial page updates:

python
return render(request, "articles/list.html#article-card", {"article": article})

On earlier versions, use the django-template-partials package.

See the templates reference for template configuration, context processors, custom tags and filters, fragment caching, and escaping rules.

Security

Django's defaults protect against SQL injection (ORM), XSS (autoescaping), CSRF (middleware), and clickjacking — don't work around them. Use the built-in Content Security Policy support (Django 6.0+) instead of the third-party django-csp package.

See the deployment reference for production security settings, HTTPS configuration, and CSP setup including nonces.

Background Tasks

Use the built-in Tasks framework (Django 6.0+) for fire-and-forget work like sending email, instead of running it inline in the request-response cycle:

python
from django.core.mail import send_mail
from django.tasks import task


@task
def send_welcome_email(to: str):
    send_mail("Welcome!", "Thanks for signing up.", None, [to])


# In a view:
send_welcome_email.enqueue(to=user.email)

See the async reference for backend configuration and production requirements. For periodic scheduling, chaining, retries, or rate limiting, use Celery.

Testing

Use TestCase with setUpTestData() for shared fixtures (created once per class, not per test), and the test client for view tests:

python
from django.test import TestCase
from django.urls import reverse

from .models import Article


class ArticleTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.article = Article.objects.create(title="Testing")

    def test_list_view(self):
        response = self.client.get(reverse("articles:list"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Testing")

instead of:

python
# DO NOT DO THIS — recreates objects for every test method
def setUp(self):
    self.article = Article.objects.create(title="Testing")

pytest with pytest-django is a fine alternative when the project already uses it. See the testing reference for choosing a test case class, Django-specific assertions, query-count tests, and async tests.

Admin

Register models with a ModelAdmin that configures list_display, list_filter, and search_fields rather than a bare admin.site.register(). The admin is for trusted staff only — never expose it as a public-facing interface, and consider changing the default /admin/ URL in production.

On Django 6.1+, use the location argument of the @admin.action() decorator to make actions available on change forms as well as the change list, and prefer explicit field names over list_select_related = True (setting it to True is deprecated).

See the admin reference for inlines, computed columns, query optimization, custom actions, and permissions.

Check the Docs, Don't Guess

Django ships a feature release roughly every eight months, and each one deprecates something. When a question turns on version-specific behavior — whether an argument exists, when something was deprecated, what a setting defaults to — fetch the docs instead of answering from memory:

Check the project's installed version before recommending a feature, and say so when a suggestion requires an upgrade:

bash
python -c "import django; print(django.get_version())"

Prefer /en/stable/ over a pinned version number in links so they don't go stale.

Tệp đi kèm

Mô hình đọc các tệp này khi cần trong lúc kỹ năng được tải. Các tệp được cung cấp ở dạng có thể đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI Django làm được gì?

Django best practices and conventions. Use when creating, refactoring, or reviewing Django projects, apps, models, views, templates, forms, admin, tests, or settings. Keeps Django code secure, idiomatic, and up to date with the latest features and patterns. Triggers on starting a Django project or app, writing models/migrations/querysets, class-based or function-based views, forms and validation, templates, the admin, tests, async views and background tasks, deployment and security settings, N+1 and slow-query debugging, and Django version upgrades.

Vì sao nên dùng Django trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Django là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Django trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/wsvincent/django-skills/tree/main. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Django?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Django với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Django với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Django có miễn phí không?

Có. Kỹ năng này được wsvincent phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇