0

I am new to Django, and I am trying to create a multiple selection with checkboxes. The problem is that all of the examples that I found have fixed choices that are specified in the form, and I don't need that.

More concretely, let this be a model for a simple car dealership app:

class CarBrand(models.Model):
    name = model.CharField()

class CarModel(models.Model):
    name = model.CharField()
    brand = model.ForeignKey(CarBrand)

My goal is when I enter the page for Audi, I get options A3, A4, A5, but when I enter the page for BMW, I get options M3, M4, M5. After clicking the submit it should send all the car models that were selected.

makons
  • 522
  • 1
  • 11
  • 27
  • What you mean by fixed choices? Normally all the checkboxes have the id of the corresponding instance, so they are not fixed. – Alexander Tyapkov Jan 10 '17 at 19:03
  • What I meant is that I don't have a static dictionary for choices. Choices depend both on which user is logged in and on which page did he/she open the form. As in the example, if BMW page is opened, M3, M4, M5 will be the choices, but if Audi page is opened, other choices will be shown. – makons Jan 12 '17 at 11:37

1 Answers1

1

Give the form an __init__ method that gets a CarBrand as a parameter, then set the queryset to choose from based on that:

class CarForm(forms.Form):
    def __init__(self, car_brand, *args, **kwargs):
        self.fields['cars'] = forms.ModelMultipleChoiceField(
            queryset=CarModel.objects.filter(brand=car_brand),
            widget=forms.CheckboxSelectMultiple)
        super(CarForm, self).__init__(*args, **kwargs)

Now in your view get the relevant CarBrand instance for the page first, the create the form with CarForm(car_brand, request.POST) etc.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
  • This is exactly what I needed. Thank you. – makons Jan 12 '17 at 11:33
  • How to access CarModel fields in template? I only get the choice_label, but I need other fields for each choice. I am trying to achieve something like this: https://postimg.org/image/trj07ajgj/ – makons Jan 17 '17 at 18:18