1

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 に答える