I want to keep user selected option active from the long SELECT OPTION dropdown list what they choose from SELECT OPTION. active mean display selected value. Like by default in select options it shows Spanish To English(first one) but if user selects French To English I want to keep selected this one
This is my HTML form in template file.
<form action="" method="post">
{% csrf_token %}
<div >
<select aria-label=".form-select-lg" name="lang_txt">
<option value="span_to_eng">Spanish To English</option>
<option value="eng_to_span">English To Spanish</option>
<option value="french_to_eng">French To English</option>
</select>
<input name="txt" type="text" placeholder="Search...">
<a href="#"><img src="/static/assets/image/search.png" alt=""></a>
</div>
</form>
This is views function
def lang_convert_view(request):
if request.method == "POST" and 'txt' in request.POST:
txt = request.POST.get('txt')
selected_lang = request.POST.get('lang_txt')
data = custom_function_name(txt)
context = {'data': data}
else:
context = {}
return render(request, 'index.html', context)
CodePudding user response:
Views:
def lang_convert_view(request):
if request.method == "POST" and 'txt' in request.POST:
txt = request.POST.get('txt')
selected_lang = request.POST.get('lang_txt')
data = custom_function_name(txt)
context = {'data': data}
else:
data = Model.objects.get(id='your query')
context = {'data': data}
return render(request, 'index.html', context)
Template:
<form action="" method="post">
{% csrf_token %}
<div >
<select aria-label=".form-select-lg" name="lang_txt">
<option value="span_to_eng" {% if data.selected_lang == 'span_to_eng' %}selected{% endif %}>Spanish To English</option>
<option value="eng_to_span" {% if data.selected_lang == 'eng_to_span' %}selected{% endif %}>English To Spanish</option>
<option value="french_to_eng" {% if data.selected_lang == 'french_to_eng' %}selected{% endif %}>French To English</option>
</select>
<input name="txt" type="text" placeholder="Search...">
<a href="#"><img src="/static/assets/image/search.png" alt=""></a>
</div>
</form>