1

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>
4

3 回答 3

2

对不起我的话,但这似乎是一个不好的方法。django 的处理方式是一个简单的表单,为您选择的选项设置一个初始值。如果您不相信我,并且您坚持这种方式,那么请更改您的模板,如果

{% if choice == myInitChoice %}

不要忘记发送myInitChoice到上下文。

c = RequestContext(request, {
    'myInitChoice': request.session.get( 'yourInitValue', None ),
})
return HttpResponse(t.render(c))
于 2012-09-01T22:04:17.343 回答
0

通常,当您遇到常见任务时,可能有一种简单的方法可以在 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})

在您的模板中:

{% if form.errors %}
    {{ form.errors }}
{% endif %}

<form method="POST" action=".">
  {% csrf_token %}
   {{ form }}
   <input type="submit" />
</form>
于 2012-09-04T17:45:53.430 回答
0
@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)

我刚刚添加takes_context='True'并从上下文中获取值。我编辑为的模板

{% 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>
于 2012-09-04T16:50:18.057 回答