Reputation: 131
For some reason I can't get this to work so please help me out..
I have a choicefield that have 3 choices in a dropdown. I can choose them the first time, and then submit. However after I hit submit, I want to choose again but my dropdown become empty...and I would have to refresh the page for it to appear again. Why?
views.py: I put forms inside because it's short
def home(request):
class My_form(forms.Form):
my_choices = [('TEST', 'TEST'), ('ABC', 'ACB'), ('XZY', 'XZY')]
symbol=forms.ChoiceField(choices=my_choices)
if request.method == 'POST':
test_form = My_form(request.POST)
if test_form.is_valid():
symbol = test_form.cleaned_data['symbol']
return render(request, 'blog/home.html',{'symbol':symbol})
else:
messages.error(request, "Error")
else:
test_form = My_form()
return render(request, 'blog/home.html', {'test_form':test_form} )
template:
{% extends "blog/base.html" %}
{% block content %}
<form width="600px" action="." method="post" >{% csrf_token %}
<div class="row align-items-start">
<div class="col-sm-5">
<label for="symbol">Stocks</label>
<select class="form-control" id="symbol" name ="symbol">
{% for key in test_form.symbol %}
<option >{{key}}</option>
{% endfor%}
</select>
{{ test_form.errors }}
{{ test_form.non_field_errors }}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
{% endblock content %}
Upvotes: 1
Views: 62
Reputation: 105
I think that in the POST part of the function, in the return line, you don't return form to the context so after successful POST the template don't have any form to render. Try something like this in the POST's return line:
return render(request, 'blog/home.html',{'symbol':symbol, 'test_form': test_form})
Upvotes: 1