4

Customizing a queryset of a form field in Django isn't a hard job. Like this

But, assuming I have the following models:

#models.py

class Work(Model):
    name = models.CharfField(...)
    #some fields

class Gallery(Model):
    work = models.ForeignKey(Work)

class Photo(Model):
   gallery = models.ForeignKey(Gallery)

class StageOfWork(Model):
    work = models.ForeignKey(Work)
    gallery = models.ForeignKey(Gallery)
    #some fields

And an admin.py like this

#admin.py

class StageOfWorkAdmin(admin.TabularInline):
    model = StageOfWork
    form = StageOfWorkForm
    extra = 1

class WorkAdmin(admin.ModelAdmin):
    inlines = [EtapaObraAdmin]

I have this problem: when I edit a Work, exists many Form Inlines of StageOfWorks, these StageOfWorks inline forms have a Gallery selector. I need to customize de queryset of this Galleries like this:

class StageOfWorkForm(ModelForm):

    def __init__(self, *args, **kwargs):        
        super(StageOfWorkForm, self).__init__(*args, **kwargs)
        if 'instance' in kwargs:
             self.fields['gallery'].queryset = Gallery.objects.filter(work__id=self.instance.work.id)

But this only works in the Forms who is editing forms. I need to get a work id in context of init method to do the right queryset anyway.

How could I do that?

2 Answers 2

4

The only way I have been able to do it is pass in the data you need into the instantiaton of the form class.

i.e., in your view:

def view(request):
    ...
    work = <whatever>
    form = StageOfWorkForm(work, request.POST)
    ...

Then, your form needs to the work object:

class StageOfWorkForm(ModelForm):
    def __init__(self, work, *args, **kwargs):
        super(StageOfWorkForm, self).__init__(*args, **kwargs)
        self.fields['gallery'].queryset = work.gallery_set.all()
3

I haven't done this exact thing, but I did something similar. I used the Smart Selects Django plugin. This can be found here: https://github.com/digi604/django-smart-selects

I've use this to a filtered select in the admin, but it was in a regular model, not an inline, but it is quite possible that the plugin works in inlines too. I'd at least check it out.

Hailey

1
  • Wow! This is a sleek sleek project! It works flawlessly for normal forms and inlines too!
    – JWL
    Jul 27, 2013 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.