Dynamic drop-down list in Django forms

[亡魂溺海] 提交于 2019-12-12 10:22:15

问题


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.


回答1:


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/



来源:https://stackoverflow.com/questions/36845918/dynamic-drop-down-list-in-django-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!