1

在我的 admin.py 中,我使用 changeform_view 方法在保存 Fo 后将一些数据保存到添加表单中,我的管理类之一是:

class temp_mainAdmin(admin.ModelAdmin):

    form = TempMainForm

    list_filter = ('t_type',)
    list_display = ('descr', 't_type', 'notes', 'dt', 'active')

    def save_model(self, request, obj, form, change):
        obj.user = request.user
        super(temp_mainAdmin, self).save_model(request, obj, form, change)

    def changeform_view(self, request, obj_id, form_url, extra_context=None):

        try:            
            l_mod = temp_main.objects.latest('id')

            extra_context = {
                'lmod': l_mod,
                'oId': obj_id
            }

            return super(temp_mainAdmin, self).changeform_view(request, obj_id,form_url, extra_context=extra_context)
    except Exception:
        pass


admin.site.register(temp_main, temp_mainAdmin, )

关键是如果 temp_main 表至少有一条记录,但如果表是空白的,当我尝试打开“添加”表单时,我会收到错误

DoesNotExist at /admin/backend/temp_main/add/ temp_add 匹配查询不存在。

如果我从我的班级中删除整个 changeform_view 方法,除了按下“保存并添加另一个”之后我没有填充我的字段的事实之外,所有的都完成了。

我的 changeform_view 方法有问题吗?

ps:我使用 PostgreeSQL 作为后端数据库

非常感谢提前

4

2 回答 2

1

您可以在方法内部以这种方式检查查询:

try:
    l_mod = temp_main.objects.latest('id')
except Exception:
    l_mod = None
于 2019-09-10T07:35:26.077 回答
0

您可以在保存之后和插入数据库之前使用带有信号方法的 pre_save 进行操作....

你也可以需要模型字段 blank=true ....

这是文档.... docs.djangoproject.com

于 2019-09-10T05:10:28.823 回答