How to configure Queryset fields from Inline admin, which uses primary form pk in Django?

Setting up a request in a form field in Django is not a difficult task. Like this

But assuming that 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 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 the Work, there are many Inlines forms from StageOfWorks, these StageOfWorks built-in forms have a gallery selector. I need to adjust the request size of this Gallery as follows:

 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 on Forms that edit forms. I need to get the job id in the context of the init method in order to make the correct set of queries anyway.

How can i do this?

+4
source share
2 answers

The only way I was able to do this was to pass the data you need into an instance of the form class.

ie, in your opinion:

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

Then your form should work with the 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
source

I did not do it for sure, but I did something similar. I used the Smart Selects Django plugin. It can be found here: https://github.com/digi604/django-smart-selects

I use this for filtered select in admin, but it was in the normal model and not in the string, but it is quite possible that the plugin works inside. I would at least check it out.

haley

+3
source

Source: https://habr.com/ru/post/1341190/


All Articles