6

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)
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Wouldn't adding `unique=True` to your ForeignKey accomplish the same goal but make sure you don't make the mistake in your code as well? – Jack M. May 11 '12 at 21:25
  • The filter is applied for two reasons, first for disable two host have the same hostuser, that could effectively solve setting unique, but the second reason is that the filter wouldn't display all hostuser to choose from (which can be hundreds) showing only those that haven't been assigned yet (it will be a few). – José Antonio Yáñez Jiménez May 11 '12 at 21:35
  • If you have resolved the issue, post it as an answer so that it will be helpful to others. – arulmr Aug 31 '12 at 10:05

1 Answers1

5

(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)
Community
  • 1
  • 1
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129