django-admin - 在 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"
保存新数据会很好,但这不是必需的。
任何指导将不胜感激
谢谢
解决方案
我意识到这可能是最好的使用方法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,
)
这似乎行得通。它将值保存在模型中,当表单加载时,它会填充现有数据和我的代码中的新数据
谢谢
授予
推荐阅读
- javascript - 如何在 ReactJS 中动态添加或删除表
- python - Django:不会自动选择特定用户的帖子
- vb.net - VB NET 如何将编码字符集以 vb 形式和附属成员
- javascript - 如何将 3 种颜色设置为同一个 chartjs 栏?
- ios - 将子层添加到没有情节提要的 UITextField 不会设置文本字段的样式
- python - 根据另一个列表中的值创建相应的 RGB 列表(颜色图)
- python-3.x - 当前线程 0x00002fe0(最近一次调用优先):
- docker - 挂载卷会覆盖存储在 Docker 映像中的文件
- html - 如何在支持所有 IE 浏览器的 UI 上创建带计时器的圆圈
- php - 通过 LAN 将在线内容共享到另一台未连接到 Internet 的计算机