21 Prompts for Building Django Backends: Models, Views, and Admin APIs

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. But even the most experienced developers hit roadblocks: designing efficient database queries, structuring views, building REST APIs, or configuring the admin interface. That's where AI prompts come in. By using carefully crafted prompts, you can get instant, expert-level guidance from AI tools, saving hours of research and debugging. In this article, I've curated 15 prompts that cover the full Django spectrum — from models and views to API and admin. Each prompt is battle-tested and comes with a real-world example and the kind of result you can expect. Whether you're a beginner or a seasoned pro, these prompts will become your secret weapon.

Basic Prompts: Getting Started with Models and Views

1. Designing a Model with Relationships

Prompt: "Act as a senior Django developer. For a blogging platform, design a set of models for Author, Post, and Comment. Include fields for title, slug, content, published date, and status. Use appropriate field types, relationships (ForeignKey, ManyToMany), and add a Meta class for ordering and unique constraints. Explain your choices."

Example Result: The AI returns a complete models.py with Author (extending Django's User via OneToOneField), Post with title, slug, content, author (ForeignKey), tags (ManyToMany to Tag), published_date, status (choices: draft, published), and Comment with post (ForeignKey), author (ForeignKey to User), body, and created_at. It also explains why slug is unique and why Meta ordering is set to -published_date.

2. Creating a List View with Pagination

Prompt: "Write a Django class-based view to list all published posts, paginated by 10. Use ListView and Paginator. Include the template code and explain how pagination works in Django."

Example Result: The AI outputs a PostListView that filters posts by status='published', sets paginate_by = 10, and a template snippet with {% for post in page_obj %} and {% include 'pagination.html' %}. It explains the page_obj context variable and how to render pagination controls.

3. Implementing a Search Form in Views

Prompt: "Create a function-based view that handles a search query for posts by title or content. Use Q objects to perform an OR search, and render results in a template. Include the URL configuration."

Example Result: The view extracts q from request.GET, uses Post.objects.filter(Q(title__icontains=q) | Q(content__icontains=q)), and passes the results to a template. The URL pattern maps /search/ to this view. The explanation covers Q objects and case-insensitive lookups.

Advanced Prompts: Queries, Forms, and Performance

4. Optimizing Queries with select_related and prefetch_related

Prompt: "Explain how to use select_related and prefetch_related in Django ORM to optimize queries for a blog. Provide a concrete example with Post and Comment models, and show the difference in SQL queries executed."

Example Result: The AI explains that select_related works for ForeignKey and OneToOne, while prefetch_related is for ManyToMany and reverse relations. It shows Post.objects.select_related('author').prefetch_related('comments') and compares the number of queries using Django's connection.queries or django-debug-toolbar.

5. Writing Custom Model Managers

Prompt: "Write a custom manager for a Django model that provides a published() method to fetch only published posts. Use a Manager subclass and explain how to use it in queries."

Example Result: The AI defines PostManager(models.Manager) with def published(self): return self.get_queryset().filter(status='published'), then sets objects = PostManager(). It shows usage: Post.objects.published() and explains that custom managers allow reusable query logic.

6. Handling Forms with File Uploads

Prompt: "Create a Django form for uploading a profile picture with validation (max size, allowed extensions). Include the model field, form class, and view that processes the upload. Mention how to configure MEDIA_ROOT and MEDIA_URL."

Example Result: The form uses forms.ImageField, a validator that checks extension and size, and a view that saves the file to request.user.profile. The AI also provides settings for MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and MEDIA_URL = '/media/', plus URL patterns to serve media in development.

7. Using Django Signals for Profile Creation

Prompt: "Show how to automatically create a Profile for each new User using Django signals. Include post_save signal, receiver function, and the code in apps.py."

Example Result: The AI writes a signal in models.py that creates a Profile instance when a User is created, and connects it in apps.py's ready() method. It also warns about using @receiver decorator and potential pitfalls.

Expert Prompts: REST API and Admin Customization

8. Building a REST API with Django REST Framework

Prompt: "Design a REST API for a blog using Django REST Framework. Create serializers for Post and Comment, viewsets with permissions (only authenticated users can create/update), and routers. Include URL configuration."

Example Result: The AI produces serializers.py with PostSerializer and CommentSerializer, viewsets.py with PostViewSet using permission_classes = [IsAuthenticatedOrReadOnly], and routers.py registering routes. It explains ModelViewSet and DefaultRouter.

9. Implementing Token Authentication in DRF

Prompt: "Add token authentication to a Django REST Framework API. Show how to set up authentication_classes, obtain a token, and authenticate requests. Provide example curl commands."

Example Result: The AI configures TokenAuthentication in settings, adds rest_framework.authtoken to INSTALLED_APPS, and shows how to create a token via Django shell or API endpoint. It includes curl examples: curl -X POST -d "username=...&password=..." /api-token-auth/.

10. Customizing the Django Admin with Inlines and Actions

Prompt: "Customize the Django admin for a Post model: use list_display, list_filter, search_fields, add inline for Comment, and create a custom admin action to publish selected posts."

Example Result: The AI defines PostAdmin(admin.ModelAdmin) with list_display = ('title', 'author', 'status', 'published_date'), search_fields = ['title', 'content'], inlines = [CommentInline], and a custom action make_published that sets status. It explains how to register actions.

11. Creating a Custom Management Command

Prompt: "Write a Django management command that deletes all posts older than 30 days. Include the command skeleton, how to run it, and best practices for management commands."

Example Result: The AI creates a BaseCommand subclass with handle() method, uses Post.objects.filter(published_date__lt=timezone.now() - timedelta(days=30)).delete(), and explains how to add arguments and test the command.

12. Implementing Caching for API Responses

Prompt: "Show how to cache API responses in Django REST Framework using cache_page decorator or django-cacheops. Provide an example with @method_decorator(cache_page(60*15)) and explain how to set up caching in settings."

Example Result: The AI demonstrates adding @method_decorator(cache_page(60*15)) to a ViewSet method, and configures CACHES in settings with LocMemCache or Redis. It also warns about cache invalidation.

13. Writing Tests for Models and Views

Prompt: "Write unit tests for a Django blog app: test model methods, view responses, and API endpoints. Use TestCase and APITestCase. Include example test code."

Example Result: The AI provides tests for Post model's __str__ and get_absolute_url, for a view's status code and template, and for API endpoints using APIClient. It explains setUpTestData and Client.

14. Deploying Django with Gunicorn and Nginx

Prompt: "Provide a step-by-step guide to deploy a Django project on Linux using Gunicorn and Nginx. Include configuration files, systemd service, and static/media file handling."

Example Result: The AI walks through installing Gunicorn, creating a systemd service file, configuring Nginx as a reverse proxy, and settings for STATIC_ROOT and MEDIA_ROOT. It includes sample nginx config and commands to restart services.

15. Using Django with PostgreSQL Full-Text Search

Prompt: "Implement full-text search in Django using PostgreSQL's SearchVector and SearchQuery. Show how to add a search view that ranks results by relevance."

Example Result: The AI uses Post.objects.annotate(search=SearchVector('title', 'content')).filter(search=SearchQuery(query)), and orders by -search. It explains the SearchRank for ranking and mentions the need for PostgreSQL.

Conclusion

These 15 prompts cover the essential aspects of Django development — from basic models to advanced API and deployment. By incorporating them into your workflow, you'll not only save time but also learn best practices from AI's vast knowledge. The key is to treat prompts as starting points: always adapt the generated code to your specific project and test thoroughly. As you become more comfortable, you'll start crafting your own prompts for even more specific challenges. So, next time you're stuck on a Django problem, remember these prompts — they might just be the boost you need. Happy coding!

← All posts

Comments