我有一個模型和一個模型來改變一些設置。該表格顯示的是正確的值,但是當我提交表單時,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