views:

901

answers:

5

Edited :-) Hopefully a bit clearer now.

The logic is of the model is:

  • A Building has many Rooms
  • A Room may be inside another Room (a closet, for instance--ForeignKey on 'self')
  • A Room can only in inside of another Room in the same building (this is the tricky part)

Here's the code I have:

#spaces/models.py
from django.db import models    

class Building(models.Model):
    name=models.CharField(max_length=32)
    def __unicode__(self):
        return self.name

class Room(models.Model):
    number=models.CharField(max_length=8)
    building=models.ForeignKey(Building)
    inside_room=models.ForeignKey('self',blank=True,null=True)
    def __unicode__(self):
        return self.number

and:

#spaces/admin.py
from ex.spaces.models import Building, Room
from django.contrib import admin

class RoomAdmin(admin.ModelAdmin):
    pass

class RoomInline(admin.TabularInline):
    model = Room
    extra = 2

class BuildingAdmin(admin.ModelAdmin):
    inlines=[RoomInline]

admin.site.register(Building, BuildingAdmin)
admin.site.register(Room)

The inline will display only rooms in the current building (which is what I want). The problem, though, is that for the inside_room drop down, it displays all of the rooms in the Rooms table (including those in other buildings).

In the inline of rooms, I need to limit the inside_room choices to only rooms which are in the current building being displayed by the main form.

I can't figure out a way to do it with either a limit_choices_to in the model, nor can I figure out how exactly to override the admin's inline formset properly (I feel like I should be somehow create a custom inline form, pass the building_id of the main form to the custom inline, then limit the queryset for the field's choices based on that--but I just can't wrap my head around how to do it).

Maybe this is too complex for the admin site, but it seems like something that would be generally useful...

Thanks again for your help!

+2  A: 

If Daniel, after editing your question, hasn't answered - I don't think I will be much help... :-)

I'm going to suggest that you are trying to force fit into the django admin some logic that would be better off implemented as your own group of views, forms and templates.

I don't think it is possible to apply that sort of filtering to the InlineModelAdmin.

celopes
+1  A: 

I have to admit, I didn't follow exactly what you're trying to do, but I think it's complex enough that you might want to consider not basing your site off of the admin.

I built a site once that started out with the simple admin interface, but eventually became so customized that it became very difficult to work with within the constraints of the admin. I would have been better off if I'd just started from scratch--more work at the beginning, but a lot more flexibility and less pain at the end. My rule-of-thumb would be if that what you're trying to do is not documented (ie. involves overriding admin methods, peering into the admin source code etc.) then you're probably better off not using the admin. Just me two cents. :)

+3  A: 

This question and answer is very similar, and works for a regular admin form

Inside of an inline--and that's where it falls apart... I just can't get at the main form's data to get the foreign key value I need in my limit (or to one of the inline's records to grab the value).

Here's my admin.py. I guess I'm looking for the magic to replace the ???? with--if I plug in a hardcoded value (say, 1), it works fine and properly limits the the available choices in the inline...

#spaces/admin.py
from demo.spaces.models import Building, Room
from django.contrib import admin
from django.forms import ModelForm


class RoomInlineForm(ModelForm):
  def __init__(self, *args, **kwargs):
    super(RoomInlineForm, self).__init__(*args, **kwargs)
    self.fields['inside_room'].queryset = Room.objects.filter(
                               building__exact=????)                       # <------

class RoomInline(admin.TabularInline):
  form = RoomInlineForm
  model=Room

class BuildingAdmin(admin.ModelAdmin):
  inlines=[RoomInline]

admin.site.register(Building, BuildingAdmin)
admin.site.register(Room)
mightyhal
+1  A: 

I found a fairly elegant solution that works well for inline forms.

Applied to my model, where I'm filtering the inside_room field to only return rooms that are in the same building:

#spaces/admin.py
class RoomInlineForm(ModelForm):
  def __init__(self, *args, **kwargs):
    super(RoomInlineForm, self).__init__(*args, **kwargs)  #On init...
  if 'instance' in kwargs:
   building = kwargs['instance'].building
  else:
 building_id = tuple(i[0] for i in self.fields['building'].widget.choices)[1]
 building = Building.objects.get(id=building_id)
  self.fields['inside_room'].queryset = Room.objects.filter(building__exact=building)

Basically, if an 'instance' keyword is passed to the form, it's an existing record showing in the inline, and so I can just grab the building from the instance. If not an instance, it's one of the blank "extra" rows in the inline, and so it goes through the hidden form fields of the inline that store the implicit relation back to the main page, and grabs the id value from that. Then, it grabs the building object based on that building_id. Finally, now having the building, we can set the queryset of the drop downs to only display the relevant items.

More elegant than my original solution, which crashed and burned as inline (but worked--well, if you don't mind saving the form partway to make the drop downs fill in-- for the individual forms):

class RoomForm(forms.ModelForm): # For the individual rooms
  class Meta:
mode = Room
  def __init__(self, *args, **kwargs):  # Limits inside_room choices to same building only
    super(RoomForm, self).__init__(*args, **kwargs)  #On init...
try:
  self.fields['inside_room'].queryset = Room.objects.filter( 
 building__exact=self.instance.building)   # rooms with the same building as this room
    except:      #and hide this field (why can't I exclude?)
 self.fields['inside_room']=forms.CharField( #Add room throws DoesNotExist error
  widget=forms.HiddenInput, 
  required=False,
  label='Inside Room (save room first)')

For non-inlines, it worked if the room already existed. If not, it would throw an error (DoesNotExist), so I'd catch it and then hide the field (since there was no way, from the Admin, to limit it to the right building, since the whole room record was new, and no building was yet set!)...once you hit save, it saves the building and on reload it could limit the choices...

I just need to find a way to cascade the foreign key filters from one field to another in a new record--i.e., new record, select a building, and it automatically limits the choices in the inside_room select box--before the record gets saved. But that's for another day...

mightyhal
A: 

Thank you for the solution, but it's not working well for me. In this line:

building_id = tuple(i[0] for i in self.fields['building'].widget.choices)[1]

You are assuming that tuple..[1] contains the foreign key value, but it's not this way all the time. If you don't save the model and go back and edit another instance, you'll get the same ordering as before, wrongly filtering the objects.

Have you checked this? I'm not sure if there's something I'm doing wrong.

Pau