记住表格选择

时间:2012-09-01 21:19:37

标签: django drop-down-menu django-templates

如何在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>

3 个答案:

答案 0 :(得分:2)

抱歉我的话,但这似乎是一个不好的方法。 django使用它的方法是选择的简单form with a initial value。如果你不相信我,并坚持这样做,那么将template if更改为:

{% if choice == myInitChoice %}

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

c = RequestContext(request, {
    'myInitChoice': request.session.get( 'yourInitValue', None ),
})
return HttpResponse(t.render(c))

答案 1 :(得分: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>

答案 2 :(得分: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>