Django动态表单,用于多选选择

时间:2018-05-02 20:00:23

标签: jquery django django-forms django-templates

我有一个Django应用程序,我要求用户在html模板上选择多个城市。城市的选择基于数据库表中不同的城市实例。由于城市总数超过100个,我想做的是让用户选择所有城市(因此他们不必手动选择100多个城市)或选择使用multiplechoicefield如果他们想要100多个城市的一些子集。我怎样才能在Django中实现它?

这是我目前正在做的代码:

forms.py

 class FilterCityForm(forms.Form):
    q = listing.objects.all().values('Address_locality').distinct().order_by('Address_locality')
    CITY_CHOICES = [[x['Address_locality'],x['Address_locality']] for x in q]
    city = forms.MultipleChoiceField(choices=CITY_CHOICES, required=True, widget=forms.SelectMultiple(attrs={'size':'30'}))

views.py

def main_select_cities(request):
    form = FilterCityForm(request.POST or None)
    city_list = dict()
    if form.is_valid():
        city_list = form.cleaned_data.get("city")
        return process_cities(request, city_list)

    context = {
        'form': form,
        'city_list': city_list,
    }
    return render(request, "0_select_cities.html", context)

模板

{% block content %}

<div class='container'>
    <div class='row'>

        <div class='col-sm-6'>
            <br><br>

        <h4>Select all the cities for which you would like to view listings</h4>    

                <form method='POST' action=''> {% csrf_token %}
                    {{form.as_p}}
                    <input class='btn btn-primary btn-lg' type='submit' value='Show listings'/>

                </form>
                <br>
                <i> use ctrl or shift + click to select multiple options</i>
        </div>  

    </div>
</div> 

{% endblock %}

0 个答案:

没有答案