我有一个模型和一个模型来改变一些设置。该表格显示的是正确的值,但是当我提交表单时,request.POST字典中缺少一个字段。Django表单缺少一个字段
模型:
class NodeSettings(models.Model):
nodetype = models.CharField(max_length=8, editable=False)
nodeserial = models.IntegerField(editable=False)
upper_limit = models.FloatField(null=True, blank=True,
help_text="Values above this limit will be of different color.")
graph_time = models.IntegerField(null=True, blank=True,
help_text="The `width' of the graph, in minutes.")
tick_time = models.IntegerField(null=True, blank=True,
help_text="Number of minutes between `ticks' in the graph.")
graph_height = models.IntegerField(null=True, blank=True,
help_text="The top value of the graphs Y-axis.")
class Meta:
unique_together = ("nodetype", "nodeserial")
视图类(我使用Django 1.3与基于类的视图):
class EditNodeView(TemplateView):
template_name = 'live/editnode.html'
class NodeSettingsForm(forms.ModelForm):
class Meta:
model = NodeSettings
# Some stuff cut out
def post(self, request, *args, **kwargs):
nodetype = request.POST['nodetype']
nodeserial = request.POST['nodeserial']
# 'logger' is a Django logger instance defined in the settings
logger.debug('nodetype = %r' % nodetype)
logger.debug('nodeserial = %r' % nodeserial)
try:
instance = NodeSettings.objects.get(nodetype=nodetype, nodeserial=nodeserial)
logger.debug('have existing instance')
except NodeSettings.DoesNotExist:
instance = NodeSettings(nodetype=nodetype, nodeserial=nodeserial)
logger.debug('creating new instance')
logger.debug('instance.tick_time = %r' % instance.tick_time)
try:
logger.debug('POST[tick_time] = %r' % request.POST['tick_time'])
except Exception, e:
logger.debug('error: %r' % e)
form = EditNodeView.NodeSettingsForm(request.POST, instance=instance)
if form.is_valid():
from django.http import HttpResponse
form.save()
return HttpResponse()
else:
return super(EditNodeView, self).get(request, *args, **kwargs)
模板的相关部分:
<form action="{{ url }}edit_node/" method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Ok" />
</form>
下面是在控制台调试输出运行调试服务器时:
2011-04-12 16:18:05,972 DEBUG nodetype = u'V10'
2011-04-12 16:18:05,972 DEBUG nodeserial = u'4711'
2011-04-12 16:18:06,038 DEBUG have existing instance
2011-04-12 16:18:06,038 DEBUG instance.tick_time = 5
2011-04-12 16:18:06,039 DEBUG error: MultiValueDictKeyError("Key 'tick_time' not found in <QueryDict: {u'nodetype': [u'V10'], u'graph_time': [u'5'], u'upper_limit': [u''], u'nodeserial': [u'4711'], u'csrfmiddlewaretoken': [u'fb11c9660ed5f51bcf0fa39f71e01c92'], u'graph_height': [u'25']}>",)
正如您所看到的,字段tick_time在requestDict中不存在于request.POST中。
应当指出的是,该领域是在网络浏览器,并查看HTML源代码时,它看起来就像在形式等领域。
任何人有什么可以是错误的任何提示?
转换为使用而不是TemplateView FormView控件,但基本问题仍然是request.POST缺少“tick_time”字段。 – 2011-04-13 07:38:04
查看编辑答案。 – 2011-04-13 15:11:01
重点已经改变,所以暂时搁置,但我会在一两周内仔细研究一下你的答案。 – 2011-04-14 10:55:57