Django - Get object id in render_change_form (ModelAdmin)

瘦欲@ 提交于 2019-12-04 20:32:09
Brian Tompsett - 汤莱恩

(Answered in a question edit. Converted to a community wiki answer. See What is the appropriate action when the answer to a question is added to the question itself? )

The OP wrote:

Solved using kwargs, the Modeladmin looks like this:

def render_change_form(self, request, context, *args, **kwargs):
    try:
        list_names = Host.objects.values_list('hostuser__id', flat=True).exclude(hostuser__id=None).exclude(hostuser__id=kwargs['obj'].hostuser.id)
    except:
        list_names = Host.objects.values_list('hostuser__id', flat=True).exclude(hostuser__id=None)
    list_names = [int(ids) for ids in list_names]
    context['adminform'].form.fields['hostuser'].queryset = HostUser.objects.exclude(id__in=list_names)
    return super(HostAdmin, self).render_change_form(request, context, args, kwargs)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!