自定义Django管理员更改列表页面

时间:2012-03-05 17:53:34

标签: django django-admin django-templates

在django-admin模型更改列表页面中,我也希望与其他模型进行交互。我的意思是,

我有三个模型

  1.Keywords

        contains name field

  2.Category
        contains category_name field

  3.Keyword Category Relation
        Category is ForeignKey and Keyword is Many to many field

在我的关键字模型changelist.html页面中,我需要自定义,更改将是

There should be a dropdown box which lists all category model objects

如果我选择一些关键字并从下拉列表中选择特定类别,则在点击保存按钮时需要在另一个模型中更新关键字和目录

应如何进行?该怎么办?建议我

1 个答案:

答案 0 :(得分:0)

您可以覆盖save_model和save_formset函数。来自我自己的代码(admin.py)的示例案例:

class SubtaskAdmin(admin.ModelAdmin):
    form = SubtaskAdminForm
    list_display = ('id', 'task', 'date_created', 'author', 'status', 'is_reclamation')
    list_filter = ('date_created', 'status', 'is_reclamation')
    actions = [change_subtask_status_to_new, change_subtask_status_to_open, change_subtask_status_to_ready]
    fields = ('order', 'task', 'tags', 'amount', 'is_reclamation', 'status')

    def save_model(self, request, obj, form, change):
        if not change:
            employee = Employee.objects.get(id=request.user.id)
            obj.author = employee
        obj.save()
        super(SubtaskAdmin, self).save_model(request, obj, form, change)

...

class MaintenanceOrderLineAdmin(admin.ModelAdmin):
        ...
        def save_formset(self, request, form, formset, change):
                instances = formset.save(commit=False)
                employee = get_object_or_404(Employee, id=request.user.id)
                for instance in instances:
                    if isinstance(instance, Subtask): 
                        instance.author = employee
                        instance.save()