2012-09-01 35 views
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> 
+1

请注明您的代码的相关部分在这里。我们不想跟随一个链接(这可能会变得无效)来找出你的代码是什么或找出它的大部分是不相关的。 – Ryan

+0

好吧,当然!你知道,第五行必须是什么? –

+0

这完全取决于你如何处理这种形式。上下文是否包含所选择的选项以匹配此选项?你问是否可以默认最后选择的选择?因为这个表单似乎没有任何验证。 –

回答

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

对不起我的话,但这似乎是一个不好的方法。 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)) 
+0

感谢您的建议:它将我推向了正确的解决方案! –

+1

hi @yakudza_m,还有另外一种方式表示感谢,有一天你会发现它。 – danihp

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> 
+0

谢谢!这也很好 –