0
0
Djangoframework~30 mins

Fieldsets for form layout in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Fieldsets for form layout
📖 Scenario: You are creating a simple Django admin form for a blog post. You want to organize the form fields into groups using fieldsets. This helps users fill the form easily by grouping related fields together.
🎯 Goal: Build a Django admin class that uses fieldsets to group the form fields title, content, and published_date into two sections: one for the main content and one for publication details.
📋 What You'll Learn
Create a Django model called Post with fields title, content, and published_date.
Create a Django admin class called PostAdmin.
Add a fieldsets attribute to PostAdmin that groups title and content under 'Content', and published_date under 'Publication Info'.
Register the Post model with the PostAdmin class.
💡 Why This Matters
🌍 Real World
Organizing form fields in Django admin helps content managers fill forms quickly and reduces errors by grouping related fields.
💼 Career
Django developers often customize admin forms for better usability and maintainability in real projects.
Progress0 / 4 steps
1
Create the Post model
Create a Django model called Post with these fields: title as a CharField with max length 100, content as a TextField, and published_date as a DateTimeField.
Django
Need a hint?

Use models.CharField for short text, models.TextField for longer text, and models.DateTimeField for date and time.

2
Create the PostAdmin class
Create a Django admin class called PostAdmin that inherits from admin.ModelAdmin.
Django
Need a hint?

Import admin from django.contrib and create a class that inherits from admin.ModelAdmin.

3
Add fieldsets to PostAdmin
Add a fieldsets attribute to PostAdmin that groups the fields as follows: a section titled 'Content' with fields 'title' and 'content', and a section titled 'Publication Info' with the field 'published_date'.
Django
Need a hint?

Use a tuple of tuples for fieldsets. Each inner tuple has a title and a dictionary with a fields key listing the fields.

4
Register Post with PostAdmin
Register the Post model with the Django admin site using admin.site.register() and the PostAdmin class.
Django
Need a hint?

Use admin.site.register() with the model and admin class as arguments.