我在创建新对象以隐藏某些字段时更改了我的管理表单,但它按字母顺序排序字段,我想按照他们在我的模型中的顺序排序。有哪些建议?
_add_fields = ('name', 'size', 'slug',
'img', 'description', 'quantity')
def get_form(self, request, obj=None, **kwargs):
model_form = super(ItemAdmin, self).get_form(
request, obj, **kwargs
)
if obj is None:
model_form._meta.fields = self._add_fields
model_form.base_fields = {
field: model_form.base_fields[field]
for field in self._add_fields
}
return model_form
答案 0 :(得分:1)
您需要使用OrderedDict
模块中的collections
来实现:
from django.contrib import admin
from collections import OrderedDict
class ItemAdmin(admin.ModelAdmin):
_add_fields = ('name', 'category',
'img', 'description', 'quantity')
def get_form(self, request, obj=None, **kwargs):
model_form = super(ItemAdmin, self).get_form(
request, obj, **kwargs
)
if obj is None:
model_form._meta.fields = self._add_fields
d = OrderedDict()
for field in self._add_fields:
d[field] = model_form.base_fields[field]
model_form.base_fields = d
return model_form