Houman
Houman

Reputation: 66320

Django: How to get selected text of DropDown in Template?

In the template I get the whole DropDown correctly shown with something like this:

{{form.deal_type}}

But what if I wanted just the text of the selected dropdown shown?

This shows me just a foreignkey.

{{form.deal_type.value}}

Upvotes: 2

Views: 6788

Answers (2)

carruthd
carruthd

Reputation: 341

I had a similar issue. To solve it I just passed the value to the template directly from the view. So in your view you presumably have something in the way of

data = {'form' :form,}    
return render_to_response('destination.html', data, context_instance = RequestContext)

In data you are passing the form that includes deal_type. Add to data a variable deal_type set equal to Object.deal_type.display_value with

data = {'form' :form,} 
if Object.deal_type: data['deal_type'] = Object.deal_type.display_value   
return render_to_response('destination.html', data, context_instance = RequestContext)   

Then on your template you can just use

{% if condition_to_show_just_text %}
    {{deal_type}} {{form.deal_type.as_hidden}}
{% else %}
    {{form.deal_type}}
{% endif %}

It may be insiginificant in this case, but it seemed to me that if the list was long, iterating with the for loop on the template would be less efficient than pulling directly from the object

Upvotes: 0

Francis Yaconiello
Francis Yaconiello

Reputation: 10919

I don't know why you want to do this exactly, but try this.

TO LOOP:

{% for value, text in form.deal_type.field.choices %}
    {{ value }}: {{ text }}
    {% if value == form.deal_type.value %}
        <strong>{{ text }}</strong> <!-- THIS IS THE SELECTED ONE... -->
    {% endif %}
{% endfor %}

EDIT:

I meant the above code as an illustration, not that you should use it verbatim. This code will do more like what you want.

{{ form.deal_type.label_tag }}
{% for value, text in form.deal_type.field.choices %}
    {% if value == form.deal_type.value %}
        {{ text }}
        <input type="hidden" name="deal_type" value="{{ value }}" />
    {% endif %}
{% endfor %}

Upvotes: 5

Related Questions