django admin 调整fieldsets的属性
时间: 2024-02-19 17:02:30 浏览: 30
在 Django Admin 中,你可以通过在模型管理类中定义 `fieldsets` 属性来调整字段集合的属性。`fieldsets` 属性允许你将表单字段分组显示,并可以更改字段的显示顺序和属性。在这个过程中,你可以通过在 `fieldsets` 属性中调整字段集合的属性来调整它们的外观和行为,例如:
```python
from django.contrib import admin
from .models import MyModel
class MyModelAdmin(admin.ModelAdmin):
fieldsets = (
('Basic Information', {
'fields': ('name', 'description')
}),
('Advanced Information', {
'classes': ('collapse',),
'fields': ('field1', 'field2', 'field3')
})
)
# customize the appearance and behavior of the Advanced Information fieldset
def get_advanced_information_fieldset(self, request, obj=None):
return {
'classes': ('wide', 'extrapretty'),
'fields': ('field1', 'field2', 'field3'),
'description': 'Please fill out all fields before submitting.'
}
def get_fieldsets(self, request, obj=None):
fieldsets = super().get_fieldsets(request, obj=obj)
if obj is None:
return fieldsets
return (
fieldsets[0],
(self.get_advanced_information_fieldset(request, obj)),
)
admin.site.register(MyModel, MyModelAdmin)
```
在这个示例中,我们定义了一个 `get_advanced_information_fieldset` 方法,该方法返回自定义的 `Advanced Information` 字段集合属性,包括 `classes`、`fields` 和 `description`。我们还通过 `get_fieldsets` 方法将自定义的 `Advanced Information` 字段集合属性添加到 `fieldsets` 属性中,并将其放在了默认的 `Basic Information` 字段集合之后。
需要注意的是,通过自定义 `get_fieldsets` 和 `get_advanced_information_fieldset` 方法,我们可以在 Django Admin 中动态调整字段集合的属性,从而实现更加灵活的布局和行为。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)