Reputation: 153
I am using select tag in template along with a link having 'submit' type inside a form tag. When I select an option from the dropdown and click on the button, it goes to the next page but I am unable to get the value of the options selected. Its showing AttributeError 'Manager' object has no attribute 'month'. Here is my code:
<form method="POST" action="{% url 'results' %}">
{% csrf_token %}
<select name="mahina" id="month">
<option value="all">All</option>
<option value="jan">January</option>
<option value="feb">February</option>
</select>
<a href="{% url 'results' %}" type="submit">Search</a>
</form>
Here is my views.py
from django.shortcuts import render
from .models import Results
def allresults(request):
results = Results.objects
if request.method == "GET":
month = results.month
year = results.year
return render(request, 'results/allresults.html', {'results': results}
Upvotes: 3
Views: 4619
Reputation: 1066
So to get the form values in the views, you must do like form_val = request.GET.get('field_name', <default_value>)
, so to add a few lines in the code
def allresults(request):
# this will get the value of the selected item, print this to know more
mahina = request.GET.get('mahina', None)
#Just writing the below query field month randomly, since the models isn't posted
results = Results.objects.filter(month=mahina)
# We don't need to give GET since by default it is a get request
# Since there are multiple objects returned, you must iterate over them to access the fields
for r in results:
month = r.month
year = r.year
return render(request, 'results/allresults.html', {'results': results}
Upvotes: 3