我在页面上有几个独立的Django表单,一切正常,但是首次访问页面时,表单自动认为自己是POST,但无效,因此表单字段在第一次访问时不可见,只有按钮。点击按钮将加载表单字段(典型的'此字段需要'错误),一旦填写,再次提交正确使用表单。如何在第一次访问页面时将空表单视为POST并且无效?我有 每个字段(在模型中)的默认设置,'初始值'视图中的设置(如下所示),我使用bootstrap和crispy-forms,虽然删除它们没有帮助。一切正常,只是“POST”和“无效问题”。
一种形式的例子:
#model
class dbPara(models.Model):
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
username = models.CharField(max_length=10)
turns = models.FloatField(default=27)
units = models.FloatField(default=5)
rise = models.FloatField(default=2.9)
rescutL = models.FloatField(default=0.0833333333)
rescutH = models.FloatField(default=0.333333333)
LorR = models.CharField(max_length=1, default='R')
def __str__(self):
return self.timestamp, self.username, self.turns, self.units, self.rise, self.rescutL, self.rescutH, self.LorR
#form
class ParaForm(ModelForm):
class Meta:
model = dbPara
widgets = {'username': forms.HiddenInput()}
fields =['username', 'turns', 'units', 'rise', 'rescutL', 'rescutH', 'LorR']
#view
def importParameters(request):
if request.method == 'GET':
form = ParaForm(initial={'turns':5, 'units':27, 'rise':2.9, 'rescutL':0.0833333333, 'rescutH':0.3333333333, 'LorR':'R'})
else:
form = ParaForm(request.POST)
if form.is_valid():
entry=dbPara(username = request.POST.get('username'),
turns = request.POST.get('turns'),
units = request.POST.get('units'),
rise = request.POST.get('rise'),
rescutL = request.POST.get('rescutL'),
rescutH = request.POST.get('rescutH'),
LorR = request.POST.get('LorR'),
)
entry.save()
return render(request, 'main.html',
{'ParaHTML' : form })
#url
url(r'^importParameters/$', 'importParameters', name='urlParameters'),
#html
<form id = "H" action="{% url "urlParameters" %}" method="post">{% csrf_token %}
{{ ParaHTML|crispy }}
<input type="hidden" name = "username" value = "{{ user.get_username }}">
<input type="submit" class="btn btn-primary" value="Set">
</form>