根据隐藏输入的模板值验证表单 - 可能吗?

时间:2015-09-05 17:52:37

标签: python django django-forms django-templates

我有一个表格,在外行人的术语中,有一堆带有值的按钮(就像复选框一样)。用户可以选择一些按钮。 按钮将它们的值(通过JQuery函数)推送到隐藏的输入中,我用它来收集值。

我想确保当用户按下提交表单时,每个隐藏输入的"values="属性不是null""

例如:确保输入等于:

<input autocomplete="off" id="id_valuePlatform" name="valuePlatform" type="hidden">

<input autocomplete="off" id="id_valuePlatform" name="valuePlatform" type="hidden" value="">

这里是forms.py:

class getGames(forms.Form):
    valuePlatform = forms.CharField(required=True, error_messages={'required': 'You need to tell us your platform(s)!'}, widget=forms.HiddenInput(attrs={'autocomplete': 'off'}))

模板:

<form method= "POST" autocomplete="off"> {% csrf_token %} 
          {{ form.non_field_errors }}
            <div class="container">
            {% if form.valuePlatform.errors %}
                <ol>
                {% for error in form.valuePlatform.errors  %}
                    <li><strong>{{ error|escape }}</strong></li>
                {% endfor %}
                </ol>
            {% endif %}
            </div>
                   {{ form.valuePlatform }}
        </div>
      </div>
</form>

Views.py:

from .forms import getGames        
def find(request):
    form = getGames()
    context = {"form": form}

    if form.is_valid():
        print form.cleaned_data['valuePlatform']

这是否可能,或者我是否必须通过Ajax POST将数据传递给Django?

1 个答案:

答案 0 :(得分:0)

在查看文档中@ Alasdair的示例之后,将views.py更改为此内容:

from .forms import getGames        
def find(request):    

    form = getGames(request.POST or None)
    context = {"form": form}

    if request.method == 'POST':
        if form.is_valid():
             print form.cleaned_data['valuePlatform']