×
   ❮   
PYTHON FOR DJANGO DJANGO FOR BEGINNERS DJANGO SPECIFICS PAYMENT INTEGRATION API BASICS Roadmap
     ❯   

MODEL ADMIN

Using Fieldsets

Using Fieldsets

Fieldsets in Django's admin interface allow you to group related fields together, making forms more organized and user-friendly.

Overview

By using fieldsets, you can enhance the visual layout of your model forms in the admin. This is particularly useful for models with many fields, allowing you to break them down into manageable sections.

Defining Fieldsets

To define fieldsets, you will use the fieldsets attribute in your ModelAdmin class. Here’s how it works:


from django.contrib import admin
from .models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    fieldsets = (
        (None, {
            'fields': ('name', 'created_at')
        }),
        ('Advanced options', {
            'classes': ('collapse',),
            'fields': ('other_field',),
        }),
    )

admin.site.register(MyModel, MyModelAdmin)

Components of Fieldsets

  •    
  • Title: The first element of each tuple is the title displayed above the fieldset. Use None if you want to omit the title.
  •    
  • Options: The second element is a dictionary where you define the fields and any additional options like CSS classes.

Collapsible Fieldsets

You can make fieldsets collapsible by adding the collapse class. This is useful for keeping the form neat:


fieldsets = (
    ('Basic Information', {
        'fields': ('name', 'created_at')
    }),
    ('Advanced Options', {
        'classes': ('collapse',),
        'fields': ('other_field',),
    }),
)

Conclusion

Using fieldsets effectively can greatly improve the usability of your Django admin interface. By grouping related fields together, you make it easier for users to navigate forms and understand the structure of your data.


References


Django-tutorial.dev is dedicated to providing beginner-friendly tutorials on Django development. Examples are simplified to enhance readability and ease of learning. Tutorials, references, and examples are continuously reviewed to ensure accuracy, but we cannot guarantee complete correctness of all content. By using Django-tutorial.dev, you agree to have read and accepted our terms of use , cookie policy and privacy policy.

© 2024 Nischal Lamichhane. All Rights Reserved.
Django-tutorial.dev is styled using Bootstrap 5.
And W3.CSS.