Django表单缺少字段

0 投票
1 回答
2737 浏览
提问于 2025-04-16 15:35

我有一个模型和一个表单,用来修改一些设置。表单显示得很好,值也都是正确的,但当我提交表单时,有一个字段在请求的 POST 数据中缺失。

这是我的模型:

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 在请求的 POST 数据中根本没有出现。

需要注意的是,这个字段在网页浏览器中是存在的,当查看 HTML 源代码时,它看起来和表单中的其他字段一样。

有没有人能给点提示,看看可能出什么问题了?

1 个回答

1

既然你在使用通用视图,难道不应该扩展一下 ProcessFormView 而不是 TemplateView 吗?

编辑

我用 TemplateView 测试了你的代码:

class EditNodeView(TemplateView):

你有没有 get_context_data 来传递表单数据?

def get_context_data(self, **kwargs):
    instance = NodeSettings.objects.get(pk=kwargs['node_id'])
    form = EditNodeView.NodeSettingsForm(instance=instance)
    context = super(EditNodeView, self).get_context_data(**kwargs)
    context['form'] = form
    return context

编辑现有对象的最佳方法是通过主键获取,我在 urls.py 里有以下内容:

url(r'^edit-node/(?P<node_id>\d+)/$', EditNodeView.as_view(), name='edit-node'),

我通过主键获取实例,可能需要在上面做一些检查,比如如果没有找到就抛出404错误。

在你的模型里,nodetypenodeserial 被设置为 editable=False,那么如果它们不可编辑,你是怎么显示或创建这些项目的呢?我为了测试把它们设置成了 True

在模板中,我把第一行改成了:

<form action="" method="POST">

我知道有很多改动,但以上的内容可以正确地查看和编辑你的模型。你可以在表单层面把 nodetypenodeserial 设置为只读,这样就可以防止别人编辑它们。

撰写回答