0

So I've been doing a lot of research trying to figure out how to filter a field based on another field's selected value (Drilldown). Below is an example of what I'm working on. I've seen some apps that looked like they might work like django-smart-selects (django: Drill down select options?), but it didn't seem like it would work for me it didn't seem as reliable as I need it to be.

forms.py 

from django.forms import ModelForm
from .models import CurriculumIntervention
from Lesson.models import Curriculum
from Lesson.models import CurriculumLesson

class CurriculumInterventionEducatorsForm(ModelForm): 

    def __init__(self, *args, **kwargs):
        super(CurriculumInterventionEducatorsForm, self).__init__(*args, **kwargs)
        curriculum = self.fields['curriculum'] #This is a ModelChoiceField

        if self.instance:
            self.fields['curriculum_lesson'].queryset= \
                CurriculumLesson.objects.filter(curriculum= **____**)#<-- what do I put here to get the curriculum's primary key value?
        else: 
            self.fields['curriculum_lesson'].queryset= None

The view and the template work fine. I just can't figure out how to get the primary key from the 1st ModelChoiceField to use for the query of the second ModelChoiceField. If I put a random id value in like 1 in the blank it filters everything to that one id. I guess I need to know how to get the selected value of a ModelChoiceField to use in the queryset. Maybe I'm on the wrong track but that's where I'm at right now. I'm wondering if maybe I have to use the view to determine the selected value and pass it to the form (like this post seems to do Django filter the queryset of ModelChoiceField)

Community
  • 1
  • 1
John R
  • 1
  • 2
  • You have the `instance`, so `self.instance.curriculum`? – solarissmoke Jul 22 '16 at 05:12
  • I've tried to do that, but I get the error message CurriculumIntervention has no curriculum. – John R Jul 22 '16 at 14:17
  • Also the curriculum = self.fields['curriculum'] line gives me the ModelChoiceField, but I'm having a hard time getting the selected value from it. – John R Jul 22 '16 at 14:22
  • "CurriculumIntervention has no curriculum" means that the object doesn't have a `curriculum` associated with it - presumably your model allows this field to be empty (or it is a foreign key). Either way this is a situation you need to handle. As for getting the selected form value... you cannot do this in the `__init__` method because the form has not been validated yet. You would have to do this in or after `is_valid()`. – solarissmoke Jul 23 '16 at 03:42
  • So how would I go about handling it a foreign key field because that's what it is. I'll look into working with the is_valid() method. I'm essentially trying to make a field filter based on the value stored in the curriculum field. – John R Jul 25 '16 at 17:01

0 Answers0