Answer the question
In order to leave comments, you need to log in
How to make a formset for multiple db objects?
There is a model with which one more model is connected by a foreign key.
class Obj(Model):
some_field = CharField(...)
class ForeignObj(Model):
obj = ForeignKey(Obj, related_name="foreign_obj")
some_data = IntegerField()
class ForeignObjForm(ModelForm):
obj = ModelChoiceField(
queryset=Obj.objects.all(),
widget=forms.HiddenInput()
)
def __init__(self, *args, **kwargs):
self.obj = kwargs.pop('obj')
super(ForeignObjForm, self).__init__(*args, **kwargs)
self.fields['obj '].initial = self.obj
class Meta:
model = ForeignObj
fields = '__all__'
Answer the question
In order to leave comments, you need to log in
I found a solution, maybe it will be useful for someone:
class ForeignObjFormSet:
def get_form_kwargs(self, index):
kwargs = super(ForeignObjFormSet, self).get_form_kwargs(index)
kwargs['obj'] = self.form_kwargs['obj'][index]
return kwargs
# Во вьюхе
def view(request):
target_objects = Obj.objects.filter(foreign_obj__isnull=True)
FormSet = formset_factory(forms.ForeignObjForm, formset=ForeignObjFormSet, extra=target_objects.count())
form_set = FormSet(form_kwargs={'obj': list(target_objects)})
# ...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question