Reputation: 1513
How to "remember" form selection value in Django?
{% load i18n %}
<form action="." method="GET" name="perpage" >
<select name="perpage">
{% for choice in choices %}
<option value="{{choice}}" {% if 'choice' == choice %} selected="selected" {% endif %}>
{% if choice == 0 %}{% trans "All" %}{% else %}{{choice}}{% endif %}</option>
{% endfor %}
</select>
<input type="submit" value="{% trans 'Select' %}" />
</form>
Upvotes: 1
Views: 2217
Reputation: 174624
Generally when you run into a common tasks, chances are there is an easy way to do it in django.
from django import forms
from django.shortcuts import render, redirect
FIELD_CHOICES=((5,"Five"),(10,"Ten"),(20,"20"))
class MyForm(froms.Form):
perpage = forms.ChoiceField(choices=FIELD_CHOICES)
def show_form(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
return redirect('/thank-you')
else:
return render(request,'form.html',{'form':form})
else:
form = MyForm()
return render(request,'form.html',{'form':form})
In your template:
{% if form.errors %}
{{ form.errors }}
{% endif %}
<form method="POST" action=".">
{% csrf_token %}
{{ form }}
<input type="submit" />
</form>
Upvotes: 0
Reputation: 1513
@register.inclusion_tag('pagination/perpageselect.html', takes_context='True')
def perpageselect (context, *args):
"""
Reads the arguments to the perpageselect tag and formats them correctly.
"""
try:
choices = [int(x) for x in args]
perpage = int(context['request'].perpage)
return {'choices': choices, 'perpage': perpage}
except(TypeError, ValueError):
raise template.TemplateSyntaxError(u'Got %s, but expected integer.' % args)
i just added takes_context='True'
and take the value from context. The template i edited as
{% load i18n %}
<form action="." method="GET" name="perpage" >
<select name="perpage">
{% for choice in choices %}
<option value="{{choice}}" {% if perpage = choice %} selected="selected" {% endif%}>
{% if choice == 0 %}{% trans "All" %}{% else %}{{choice}}{% endif %}</option>
{% endfor %}
</select>
<input type="submit" value="{% trans 'Select' %}" />
</form>
Upvotes: 0
Reputation: 51665
sorry about my words, but this seems a bad aproach. The django way to work with this is a simple form with a initial value for your selected choice. If you don't belive me, and you persist in this way, then change your template if as:
{% if choice == myInitChoice %}
Don't forget to send myInitChoice
to context.
c = RequestContext(request, {
'myInitChoice': request.session.get( 'yourInitValue', None ),
})
return HttpResponse(t.render(c))
Upvotes: 2