django field set
时间: 2023-10-16 22:08:22 浏览: 103
A field set in Django is a way to group together related fields in a form. It allows you to organize the fields in a more logical and user-friendly way, making it easier for users to understand and complete the form.
To define a field set in Django, you can use the "fieldsets" attribute in your model admin class. This attribute takes a list of tuples, where each tuple represents a field set. Each tuple contains two elements: the title of the field set and a dictionary of fields to include in the set.
Here's an example of how to define a field set in a model admin class:
```
from django.contrib import admin
from .models import MyModel
class MyModelAdmin(admin.ModelAdmin):
fieldsets = (
('Main Info', {
'fields': ('name', 'description', 'image')
}),
('Optional Info', {
'fields': ('category', 'price', 'is_featured'),
'classes': ('collapse',),
}),
)
admin.site.register(MyModel, MyModelAdmin)
```
In this example, we define two field sets: "Main Info" and "Optional Info". The "Main Info" set includes the fields "name", "description", and "image". The "Optional Info" set includes the fields "category", "price", and "is_featured", and has a CSS class of "collapse" to make it collapsible by default.
When you view the form in the Django admin, the fields will be grouped into the specified field sets, making it easier to read and fill out the form.
阅读全文