Django - Get object id in render_change_form (ModelAdmin)

只谈情不闲聊 提交于 2019-12-21 23:29:37

问题


I have these two models and modeladmin. When adding a new host in the list of available hostuser only appear hostusers that are not assigned to another host. The issue is if I edit an already created host its actual hostuser id is also filtered so I want to do is to exclude hostuser id that is currently assigned. How I can specify in the exclude the current id from the hostuser field?

The statement that I need is written between *

Thanks in advance

Models.py

class HostUser(models.Model):
    name = models.CharField(max_length=200)
    {..More Data..}

class Host(models.Model):
    {..More Data..}
    hostuser = models.ForeignKey(HostUser, blank=True, null=True)

Admin.py

class HostAdmin(admin.ModelAdmin):
    {..More Data..}
    def render_change_form(self, request, context, *args, **kwargs):
        list_names = Host.objects.values_list('hostuser__id', flat=True).exclude(hostuser__id=None).exclude(hostuser__id=**ACTUAL HOSTUSER_ID**)
        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)

回答1:


(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)


来源:https://stackoverflow.com/questions/10556288/django-get-object-id-in-render-change-form-modeladmin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!