Django:在下拉列表中显示字典的值

时间:2015-05-01 11:17:32

标签: python django templates dictionary dropdownbox

在我的模板中,下拉框中填充了字典而不是字典的值。如何只显示该值?

这是我的collectionPoint

class CollectionPoint(models.Model):
    addressID = models.AutoField(primary_key=True)
    collectionPointName = models.CharField(max_length=50, null=False)
    street = models.CharField(max_length=50, null=False)
    streetnumber = models.CharField(max_length=20, null=False)
    city = models.CharField(max_length=50, null=False)
    postalcode = models.CharField(max_length=30, null=True)
    gps_latitude = models.FloatField(blank=True, null=True)
    gps_longitude = models.FloatField(blank=True, null=True)
    country = models.ForeignKey(Country)
    company = models.ForeignKey(Company)

    #only the name is returned to the user
    def __str__(self):
        template = '{collectionPointName}'
        return template.format(collectionPointName=self.collectionPointName)

我想显示收集点的所有不同城市

class RentalSelectCityForm(forms.Form):
    city = forms.ModelChoiceField(queryset=CollectionPoint.objects.order_by().values('city').distinct(),initial=0)

我的观点

@login_required
def rentalselectcity(request):
    # Get the context from the request.
    context = RequestContext(request)

    # A HTTP POST?
    if request.method == 'POST':
        form = RentalSelectCityForm(request.POST)

        # Have we been provided with a valid form?

        return HttpResponseRedirect('/')
    else:
        # If the request was not a POST, display the form to enter details.
        form = RentalSelectCityForm()

    context['path'] = [{'name': 'My rentals', 'url': reverse('rentals-list')}]
    context['path'] += [{'name': 'Select city', 'url': reverse('rental-select-city')}]

    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    return render_to_response('user/rentalselectcity.html', {'form': form}, context)

我的模板

{% block content %}
<div class="box box-default">
    <!--<div class="box-header">
        <h3 class="box-title">Title</h3>
    </div>--><!-- /.box-header -->
    <!-- form start -->
    <form action="{% url 'rental-select-city' %}" method="post" role="form">
        {% csrf_token %}
        <div class="box-body">
            {{ form.non_field_errors }}
            <div class="form-group">
                {{ form.city.errors }}
                <label for="{{ form.city.id_for_label }}">Select a city</label>
                {{ form.city|attr:"class:form-control" }}
            </div>
        </div>
        <!-- /.box-body -->
        <div class="box-footer">
            <button type="submit" class="btn btn-primary">Select city</button>
        </div>
    </form>
</div><!-- /.box -->
{% endblock %}

1 个答案:

答案 0 :(得分:2)

您可以将表单字段查询集更改为

CollectionPoint.objects.order_by().values_list('city', flat=True).distinct() 

请参阅values_list docs以获取参考资料