0
我有一種外行人的形式,有一堆按鈕(表現爲複選框)與值。用戶可以選擇一些按鈕。 按鈕將它們的值(通過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的?
它並不形式值是否是使用JavaScript或沒有設置之至Django的。上面的例子應該可以工作。如果它不起作用,那麼在你的視圖中打印'request.POST'和'form.errors'可能會幫助你看到你提交的數據。 – Alasdair
它確實有效,但我希望表單在值爲空或空時拋出一個錯誤。 – AllTheGoodNamesWereTaken
您是否檢查過消息是否出現在'form.errors'中?你如何在模板中顯示公司錯誤?你看過[渲染表單錯誤文檔](https://docs.djangoproject.com/en/1.8/topics/forms/#rendering-form-error-messages)嗎? – Alasdair