zallarak
zallarak

Reputation: 5515

Multi input in Django

How can you pass multiple object IDs into a Django form? Is there a way to pass in a JavaScript Array containing multiple object IDs into a form field and iterate through it on the server side?

Upvotes: 0

Views: 120

Answers (2)

Filip Dupanović
Filip Dupanović

Reputation: 33650

You can use the CommaSeparatedIntegerField to store the IDs, perhaps even with a HiddenInput widget if your populating the data dynamically in JavaScript.

You'll be able to iterate through a list of integers from your form's cleaned_data after you validate the form on the server side.

Upvotes: 1

Andrea Di Persio
Andrea Di Persio

Reputation: 3266

You may want to create a new Field and override the 'to_python' method.

The following basic example create a new char field which accept a string containing ids separated by comma and return a query set.

class MyField(forms.CharField):
    def to_python(self, value):
        ids = value.split(',')

        return MyModel.objects.filter(id__in=ids)

class MyForm(forms.Form):
    ids = MyField()

Have a look at how validation work in Django.

Upvotes: 0

Related Questions