首页 > 解决方案 > 在 changeform_view 上填充一个字段

问题描述

例如,当我在模型中打开一个项目时:/shop_push/shopapidefinition/4/change/我想用我自己的值填充一个字段,而其余部分保持不变。

我现在可以在编辑时做一些事情,如下所示

class ShopApiDefinitionAdmin(admin.ModelAdmin):
    def __init__(self, *args, **kwargs):
        # let's define this so there's no chance of AttributeErrors
        self._request = None
        super(ShopApiDefinitionAdmin, self).__init__(*args, **kwargs)

    def get_request(self):
        return self._request

    def changeform_view(self, request, *args, **kwargs):
        # stash the request
        self._request = request
        print "changelist_view ShopApiDefinitionAdmin"

        # call the parent view method with all the original args
        # ShopApiDefinitionAdmin['about_the_shop'] = "hello"
        return super(ShopApiDefinitionAdmin, self).changeform_view(request, *args, **kwargs)

例如,我不知道如何将数据添加到该记录的字段中

field['about_the_shop'] = "new text"

保存新数据会很好,但这不是必需的。

任何指导将不胜感激

谢谢

标签: django-admin

解决方案


我意识到这可能是最好的使用方法change_view,并且在从模型中检索内容之前触发,所以我所做的是使用object_id,查询记录,执行我的代码,然后保存详细信息

def change_view(self, request, object_id, form_url='', extra_context=None):
    # Get the record
    obj = ShopApiDefinition.objects.get(id=object_id)
    # get a value as I use that in my code
    self.password = obj.password
    # do some code
    shopify_shop = "a value from my code"
    obj.about_the_shop = shopify_shop  # change field
    obj.save()  # this will update only

    return super(ShopApiDefinitionAdmin, self).change_view(
        request, object_id, form_url, extra_context=extra_context,
    )

这似乎行得通。它将值保存在模型中,当表单加载时,它会填充现有数据和我的代码中的新数据

谢谢

授予


推荐阅读