0

I'm tearing hair out here trying to do something that feels like it should be simple, but I can't work out how to do this in Django.

I have three models.

class Survey()
  name = models.CharField(max_length=100)

class Reference()
  field = models.ForeignKey(Survey)

class SurveyItem()
  field = models.ForeignKey(Survey)
  reference = models.ForeignKey(Reference, blank=True, null=True)

I want to be able to show these on a single form, so when a user has created a survey and added some references for their survey, they are then able to choose add SurveyItems with that Reference in the inline part of the form.

class SurveyInfoItemInline(admin.TabularInline):
    model = SurveyInfoItem
    extra = 3

class ReferenceItemInline(admin.TabularInline):
    model = Reference
    extra = 2

class StaticSurveyAdmin(admin.ModelAdmin):

    inlines = [ReferenceItemInline, SurveyItemInline]

I currently have this form created, and it's clunky, but people can make submissions successfully with it.

However, but I can't see a way to scope an inline form, so that when users are creating SurveyInfoItems on a Survey with the SurveyInfoItemInline widget, they only choose from References that were added previously to this survey, rather than showing all the References in the table on an app.

I've looked through stackoverflow, and found a few similar questions:

But pretty much everything I've tried has failed to affect how many References are available to choose from.

Community
  • 1
  • 1
Chris Adams
  • 2,721
  • 5
  • 33
  • 45
  • 1
    https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey ? (also works for Inlines) – NightShadeQueen Jul 08 '15 at 17:28

1 Answers1

0

This may not be the answer you're looking for, but I'd say your best bet here is to write a small JavaScript function for your admin page to hide unwanted SurveyItem choices based on currently selected References. Afterwards, you can do validation/cleanup in your admin save() method.

If you want to do everything server-side, the user experience will have to take at least two requests (page loads): the first one to set the survey references, and the next one to filter survey items using those references. Even then, the options still won't adjust in real-time when the user is adding/removing survey references on the page. It's a good question nevertheless--there isn't an obvious way to get the parent model data in the tabularInline (e.g. Prepopulating inlines based on the parent model in the Django Admin )--but I think overall it might be the least headache approaching this with JS.

Community
  • 1
  • 1
SMX
  • 1,372
  • 15
  • 14