我想非常容易地创建一个Django form
,而不是想从两个字段中获取值。
这是我的表格:
class SettingsForm(forms.Form):
download_validity = forms.CharField(label='Expiry Download')
flag_validity = forms.CharField(label='Expiry Flag')
def __init__(self, *args, **kwargs):
super(SettingsForm, self).__init__(*args, **kwargs)
然后,我有一个视图:
class SettingsView(FormView):
template_name = 'settings.html'
form_class = SettingsForm
def get_context_data(self, **kwargs):
subtitle = _("Manage Settings")
context_data = super(SettingsView, self).get_context_data(**kwargs)
context_data['subtitle'] = subtitle
return context_data
def form_valid(self, form):
download_validity = form.cleaned_data['download_validity']
flag_validity = form.cleaned_data['flag_validity']
print(download_validity)
print(flag_validity)
return super(SettingsView, self).form_valid(form)
最后是我的模板视图:
{% block main %}
<div class="container">
<div class="row">
<form autocomplete="off" method="get" action="">
<fieldset>
<legend class="title"><span class="name">{% trans 'Expiry Download link' %}</span></legend>
</fieldset>
{{ form.download_validity|as_crispy_field }}
<input type="submit" class="btn btn-default" name="UpdateDownload" value="{% trans 'Update' %}"/>
</form>
</div>
<div class="row">
<form autocomplete="off" method="get" action="">
<fieldset>
<legend class="title"><span class="name">{% trans 'Expiry New Publication' %}</span></legend>
</fieldset>
{{ form.flag_validity|as_crispy_field }}
<input type="submit" class="btn btn-default" name="UpdateFlag" value="{% trans 'Update' %}"/>
</form>
</div>
</div>
{% endblock main %}
我不知道为什么,但是我希望通过cleaned_data获得价值,但是print函数什么也不会显示。我不知道我是否错过了一些东西,但是一切似乎都是正确的。
我必须在forms.py文件中创建两个表单,而不是一个?
答案 0 :(得分:0)
在模板中,您应该在行外创建表单,如下所示:
<form ...>
<div class="row">
<input .../>
</div>
<div class="row">
<input .../>
</div>
</form>
您确定表格既有效又被发布了吗? (您可以只在视图中进行调试,然后再打印一些检查请求是否为POST等的打印件。也许您还缺少CSRF-Token,因为它未在模板中定义(https://docs.djangoproject.com/en/2.1/ref/csrf/)>
您还可以让表单自己呈现。例如,根据您的情况(https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html)通过{% crispy form %}