Create multiple choice field dynamically

My purpose is to create a django form to select devices filtered by country and club fields. My form is this:

class MyForm(Form):
    country = ChoiceField(choices=some_choices, initial=None)
    club = CharField(widget=Select())
    expiration_date = DateField()
    sales_info = ChoiceField(choices=SALES_TYPES, initial=None)
    devices = MultipleChoiceField(widget=CheckboxSelectMultiple(choices=[]))
    def clean_devices(self):
        devices = self.cleaned_data.get("devices")
        if not devices:
            raise ValidationError("At least one device must be selected.")
        return devices

    def save(self):

class MyFormView(LoginRequiredMixin, FormView):
    template_name = "store/my_template.html"
    form_class = MyFormView

    def get_success_url(self):
        return reverse('init_device')

    def form_valid(self, form):
        init_device =
        if init_device:
            return super().form_valid(form)

        return super().form_invalid(form)

    def form_invalid(self, form):


    <form action="{% url 'init_device' %}" method="post">
        {% csrf_token %}
        <select id="id_devices" name="devices" multiple>

I populate select field via javascript in this way:

let device_select = document.getElementById("id_devices");
        serialIds.forEach(serialId => {
            let option = document.createElement("option");
            option.text = serialId;
            option.value = serialId;

I obtained filtered devices form db using a websocket by now I can't pass them to the form because this error raises: ValueError: The view path.view didn't return an HttpResponse object. It returned None instead.

Then I print form.errors and this is showed <ul class="errorlist"><li>devices<ul class="errorlist"><li>Select a valid choice. device_attriubte is not one of the available choices.</li></ul></li></ul>

Can anyone help me? Thank you in advance!

Too much at once?

First get the user's choice of country and club and validate them as far as possible. When done, redirect to an URL such as


and in the view which gets invoked, use kwargs country and club in the queryset of its form's ModelMultipleChoiceField. This normalizes to a list of model instances (device objects) when the form validates.

(I'm assuming that devices are objects in your DB. THis is implied by your use of "filtered" but isn't explicit).

Back to Top