Filter Queryset in Django inlineformset_factory
Posted
by Dave
on Stack Overflow
See other posts from Stack Overflow
or by Dave
Published on 2010-04-05T20:42:23Z
Indexed on
2010/04/05
20:43 UTC
Read the original article
Hit count: 635
I am trying to use inlineformset_factory to generate a formset. My models are defined as:
class Measurement(models.Model):
subject = models.ForeignKey(Animal)
experiment = models.ForeignKey(Experiment)
assay = models.ForeignKey(Assay)
values = models.CommaSeparatedIntegerField(blank=True, null=True)
class Experiment(models.Model):
date = models.DateField()
notes = models.TextField(max_length = 500, blank=True)
subjects= models.ManyToManyField(Subject)
in my view i have:
def add_measurement(request, experiment_id):
experiment = get_object_or_404(Experiment, pk=experiment_id)
MeasurementFormSet = inlineformset_factory(Experiment, Measurement, extra=10, exclude=('experiment'))
if request.method == 'POST':
formset = MeasurementFormSet(request.POST,instance=experiment)
if formset.is_valid():
formset.save()
return HttpResponseRedirect( experiment.get_absolute_url() )
else:
formset = MeasurementFormSet(instance=experiment)
return render_to_response("data_entry_form.html", {"formset": formset, "experiment": experiment }, context_instance=RequestContext(request))
but i want to restrict the Measurement.subject field to only subjects defined in the Experiment.subjects queryset. I have tried a couple of different ways of doing this but I am a little unsure what the best way to accomplish this is. I tried to over-ride the BaseInlineFormset class with a new queryset, but couldnt figure out how to correctly pass the experiment parameter.
© Stack Overflow or respective owner