Django 2.1 admin.py changeform_view 空白表的方法错误

Django 2.1 admin.py changeform_view method error with blank tables

在我的 admin.py 中,我使用 changeform_view 方法在保存后将一些数据保存到添加表单中 例如,我的一位管理员 class 是:

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 table 至少有一条记录,则一切都已完成,但如果 table 是空白,当我尝试打开 "add" 形式我收到错误

DoesNotExist at /admin/backend/temp_main/add/ temp_add matching query does not exist.

如果我从我的 class 中删除整个 changeform_view 方法,除了在按下 "Save and add another" 之后我没有填充我的字段之外,其他都已完成。

我的 changeform_view 方法有误吗?

p.s.: 我使用 PostgreeSQL 作为后端数据库

非常感谢

您可以使用 pre_save with signal 方法进行保存之后和插入数据库之前的操作....

您还可以需要模型字段 blank=true ....

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

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

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