Search code examples
pythondjangoformsdrop-down-menumodels

Dynamic drop-down list in Django forms


I'm trying to add a dynamic drop-down list in my Django account registration form.

forms.py:

class CompanySignupForm(account.forms.SignupForm):
    first_name = forms.CharField(
        label="First Name",
        max_length=30,
        widget=forms.TextInput(),
        required=True)

    last_name = forms.CharField(
        label="Last Name",
        max_length=30,
        widget=forms.TextInput(),
        required=True)

    company = forms.CharField(
        label="Company Name",
        max_length=60,
        widget=forms.TextInput(),
        required=True)

models.py:

class EmployerProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)

    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    company = models.CharField(max_length=40)

    def __unicode__(self):
        return self.company

The question is, if I want the field "company" to be a drop-down list consisting of about 10,000 entries, what's the best way to approach this? Should I be using JS and JSON data? jQuery for autocomplete? I just want to do it in the most effective way possible.


Solution

  • Are you sure you want a dropdown with 10,000 entries? Is so, in forms.py:

    class CompanySignupForm(forms.ModelForm):
        company = forms.ChoiceField(choices=["10,000", "entries", "here"])
    

    https://docs.djangoproject.com/es/1.9/ref/forms/fields/#choicefield

    But I would opt for an autocomplete field, using http://django-autocomplete-light.readthedocs.org/en/master/