开发者

How to customize a Queryset of a Field from a admin Inline that uses a pk of the primary form in Django?

开发者 https://www.devze.com 2023-02-13 11:41 出处:网络
Customizing a queryset of a form field in Django isn\'t a hard job. Like this But, assuming I have the following models:

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 li开发者_StackOverflow中文版ke 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?


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消