15 Prompts for Django: From Models to REST API — A Developer’s Battle-Tested Toolkit
If you write Django code daily, you’ve probably already used an AI assistant to generate boilerplate, fix bugs, or refactor views. But the real power comes from crafting precise prompts — the kind that turn AI from a mediocre junior into a productivity multiplier.
This article is a living collection of 15 prompts I actually use in my workflow. Each one is battle-tested, includes a concrete example, and is formatted like a Telegram channel post for developers: no fluff, just value.
Why These Prompts Work
Generic prompts like “write a Django model” produce generic code. To get production-ready output, you need:
- Context — framework version, database backend, DRF or not.
- Constraints — naming conventions, validation rules, performance requirements.
- Examples — show the AI what you expect.
All prompts below follow the same pattern: role + task + context + constraints + output format.
1. Model Definition with Validation
Prompt:
Act as a senior Django developer. Write a Django model `Order` with fields:
- `id` (AutoField, primary key)
- `user` (ForeignKey to User, CASCADE)
- `total` (DecimalField, max_digits=10, decimal_places=2)
- `status` (CharField, choices: PENDING, PAID, SHIPPED, CANCELLED, default=PENDING)
- `created_at`, `updated_at` (auto_now_add / auto_now)
Add model-level validation: `total` must be > 0. Override `save()` to call `full_clean()`. Include `__str__`, `Meta` with ordering by `-created_at`, and a custom manager method `paid_orders()`.
Output only the code, no explanation.
Why it works: The prompt specifies choices as a tuple, validation logic, manager method, and output format. The AI produces a ready-to-paste model.
2. DRF Serializer with Nested Objects
Prompt:
You are a Django REST Framework expert. Given these models:
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=6, decimal_places=2)
Write a `BookSerializer` that:
- Includes nested `AuthorSerializer` (read-only for create/update)
- Validates that `price` is not negative
- Has a custom `create()` that accepts `author_id` as a write-only field
Use ModelSerializer. Output only the serializers.py code.
Why it works: Nested serializers are a common pain point. This prompt covers read/write asymmetry and custom creation logic.
3. Class-Based View with Mixins
Prompt:
Senior Django dev needed. Write a class-based view `OrderDetailView` that:
- Uses `LoginRequiredMixin`, `UserPassesTestMixin`
- Only allows the order owner or staff to view
- Fetches order by UUID (slug field) from URL
- Returns a 404 if not found
- Renders `orders/detail.html` with context `{'order': order}`
- Handles POST to cancel order (change status to CANCELLED)
Write the view, URL pattern (path), and test that a non-owner gets 403.
Why it works: Combines authentication, authorization, slug lookup, and POST handling — exactly what real views need.
4. Django Admin Customisation
Prompt:
Act as Django admin expert. Customise the admin for `Product` model with:
- `list_display`: name, category, price, stock, is_active
- `list_filter`: category, is_active, created_at
- `search_fields`: name, description
- `ordering`: -created_at
- `readonly_fields`: created_at, updated_at
- `fieldsets`: separate basic info, pricing, metadata
- Inline for `ProductImage` model (stacked inline)
- Custom action `make_active` that sets is_active=True for selected products
Write the complete admin.py.
Why it works: Admin customisation is repetitive. This prompt covers all common customisations in one go.
5. Django Management Command
Prompt:
You are a Django developer. Write a management command `export_orders` that:
- Takes a required argument `--start-date` and `--end-date` (date format YYYY-MM-DD)
- Exports orders in that range as CSV to stdout
- Columns: id, user_email, total, status, created_at
- Uses `csv.writer` with proper quoting
- Handles empty results gracefully (print "No orders found" to stderr)
- Uses `BaseCommand` style
Output only the command code.
Why it works: Management commands are often overlooked in prompts. This one includes argument parsing, CSV output, and error handling.
6. Signal Handler for Post-Save Actions
Prompt:
Senior Django backend dev. Write a `post_save` signal for `Order` model that:
- When an order status changes to PAID, send a confirmation email (use `send_mail` from django.core.mail)
- Log the action to a custom `OrderLog` model (fields: order, action, timestamp)
- Disconnect the signal during fixture loading (use `raw=True` check)
- Use `@receiver` decorator
Write the signals.py and the connection in apps.py.
Why it works: Signal best practices — raw save check, logging, and proper connection.
7. Django REST Framework ViewSet with Permissions
Prompt:
Django REST Framework pro. Create a `ModelViewSet` for `Article` model:
- Uses `ArticleSerializer`
- Permission classes: `IsAuthenticatedOrReadOnly` for list/retrieve, `IsAdminUser` for create/update/destroy
- Override `get_queryset` to return only published articles for unauthenticated users
- Add a custom action `@action(detail=True, methods=['post'])` called `publish` that sets `is_published=True`
- Use `DefaultRouter` in urls.py
Write views.py, serializers.py, urls.py.
Why it works: Covers dynamic permissions, custom actions, and router setup — the bread and butter of DRF.
8. Database Query Optimisation
Prompt:
Act as Django ORM optimisation specialist. Given this slow view:
class OrderListView(ListView):
model = Order
queryset = Order.objects.all()
Optimise it to:
- Use `select_related('user')` and `prefetch_related('items__product')`
- Add pagination (20 per page)
- Add a filter by status via GET parameter
- Annotate total count of items per order
- Write a test that checks the number of SQL queries (using `assertNumQueries`)
Output the optimised view and test.
Why it works: Real performance issues — N+1 queries, pagination, annotations, and testing.
9. Custom Middleware
Prompt:
Django middleware expert. Write a middleware `RequestTimingMiddleware` that:
- Records the time of each request (using `time.perf_counter`)
- Adds a header `X-Request-Time` with the duration in milliseconds to the response
- Logs requests that take longer than 1 second to `django.request` logger
- Is compatible with Django 5.0+
Write the middleware class and how to add it to settings.MIDDLEWARE.
Why it works: Middleware is a black box for many. This prompt creates a practical, measurable tool.
10. Django Test with Factory Boy
Prompt:
You are a TDD advocate. Write a test for `Order.cancel()` method that:
- Uses `factory_boy` to create a User and Order
- Calls `order.cancel()`
- Asserts status becomes CANCELLED
- Asserts a `OrderLog` entry was created with action 'cancelled'
- Uses `pytest-django` with `@pytest.mark.django_db`
- Also test that cancelling an already-shipped order raises `ValidationError`
Write the factories.py and test_models.py.
Why it works: Factory Boy + pytest-django is the modern standard. The prompt covers positive and negative cases.
11. Celery Task for Async Email
Prompt:
Senior Django + Celery developer. Write a Celery task `send_order_confirmation` that:
- Takes `order_id` as argument
- Fetches the Order (with select_related user)
- Renders an HTML email template `emails/order_confirmation.html`
- Sends via `send_mail` with `html_message`
- Retries up to 3 times on `smtplib.SMTPException` with exponential backoff
- Logs success/failure
- Uses `@shared_task` decorator
Write tasks.py and the task call from the signal (from prompt #6).
Why it works: Async tasks are essential for production. This covers retries, templates, and integration.
12. Django Debug Toolbar Configuration
Prompt:
Act as a performance consultant. Write a `settings/local.py` configuration for `django-debug-toolbar` that:
- Shows only in DEBUG=True
- Includes panels: SQL, Request, Templates, Cache, Signals
- Configures INTERNAL_IPS for Docker (use `show_toolbar_callback` to always show if DEBUG)
- Sets `SHOW_COLLAPSED = True`
- Adds jQuery CDN for toolbar UI
Write the settings snippet and the URL configuration in urls.py.
Why it works: Debug Toolbar setup is tricky with Docker. This prompt solves a common pain point.
13. Django REST Framework Throttling
Prompt:
Django REST API architect. Implement throttling for a public API:
- `AnonRateThrottle`: 100 requests/hour
- `UserRateThrottle`: 1000 requests/hour
- Custom throttle `BurstRateThrottle` that allows 10 requests/minute, then blocks for 60 seconds
- Apply `BurstRateThrottle` globally, others per viewset
- Add `X-RateLimit-Remaining` header to responses via custom exception handler
Write throttles.py, settings, and the custom exception handler.
Why it works: Throttling is often forgotten until production. Custom burst throttle is a real requirement.
14. Django ORM Aggregation and Annotation
Prompt:
Django ORM expert. Write queries that:
1. Annotate each category with total revenue from paid orders (sum of order totals)
2. Annotate each user with their last order date
3. Filter users who have placed more than 5 orders
4. Get the top 10 products by quantity sold
Use `aggregate`, `annotate`, `FilteredAggregation` (for conditional sums). Output only the ORM code.
Why it works: Complex aggregations are a frequent need for reports and dashboards.
15. Django Model Inheritance (Multi-Table vs Proxy)
Prompt:
Django model design expert. Explain with code examples:
1. Multi-table inheritance: `Student` and `Teacher` inheriting from `Person`
2. Proxy model: `Organizer` as proxy of `User` with custom manager `organizers = Organizer.objects.all()`
3. Abstract base class: `TimestampedModel` with created_at/updated_at
For each, write the models, show the database tables created, and discuss when to use which.
Why it works: Model inheritance is a common source of confusion. A comparative example clarifies trade-offs.
Bonus: How to Make These Prompts Yours
- Add your project’s naming conventions — e.g., "Use snake_case for fields, PascalCase for classes."
- Specify Python version — "Target Python 3.12, Django 5.0."
- Request tests — "Include pytest tests for edge cases."
Conclusion
These 15 prompts cover the most common Django tasks — from models to async tasks. They are not theoretical; they are the exact prompts I use to generate production code that passes code review with minimal changes.
The key is to treat AI as a senior developer you brief before they write code. Give it context, constraints, and a clear output format. The results will surprise you.
If you want to integrate Django with external services like Stripe or Salesforce, ASI Biont supports connecting to these APIs through its course platform — learn more at asibiont.com/courses.
Start using these prompts today and cut your boilerplate time by half.
Comments