如何在django formset中显示隐藏的autofield [英] How to show hidden autofield in django formset

查看:376
本文介绍了如何在django formset中显示隐藏的autofield的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,隐藏使用表单集显示的Django自动域。什么是最好的方式显示?

A Django autofield when displayed using a formset is hidden by default. What would be the best way to show it?

目前,该模型被声明为,

At the moment, the model is declared as,

class MyModel:
   locid = models.AutoField(primary_key=True)
   ...

当使用Django表单呈现时,

When this is rendered using Django formsets,

class MyModelForm(ModelForm):
  class Meta:
    model = MyModel
    fields = ('locid', 'name')

它显示在页面上,

<input id="id_form-0-locid" type="hidden" value="707" name="form-0-locid"/>

感谢。

编辑

我创建了这样的表单 -

I create the formset like this -

LocFormSet = modelformset_factory(MyModel) 
pformset = LocFormSet(request.POST, request.FILES, queryset=MyModel.objects.order_by('name')) 






第二次修改

看起来我没有使用我在那里定义的自定义表单类,所以问题需要稍微修改。

Looks like I'm not using the custom form class I defined there, so the question needs slight modification..

如何从自定义表单(将显示隐藏字段)以及使用自定义查询器创建表单?

此刻,我可以从BaseModelFormSet类继承,并使用自定义查询集,也可以使用ModelForm类将自定义字段添加到表单。有没有办法做一个表单?

At the moment, I can either inherit from a BaseModelFormSet class and use a custom query set, or I can use the ModelForm class to add a custom field to a form. Is there a way to do both with a formset?

第三次修改

我正在使用

class MyModelForm(ModelForm):
  def __init__(self, *args, **kwargs):
    super(MyModelForm, self).__init__(*args, **kwargs)
    locid = forms.IntegerField(min_value = 1, required=True)
    self.fields['locid'].widget.attrs["type"] = 'visible'
    self.queryset = MyModel.objects.order_by('name')
  class Meta:
    model = MyModel
    fields = ('locid', 'name')

LocFormSet = modelformset_factory(MyModel, form = MyModelForm)
pformset = LocFormSet()

但这仍然不是


  • 显示locid

  • 使用指定的自定义查询。

推荐答案

好的,上面的方法都没有为我工作。我从模板方面解决了这个问题,最后。

Okay, none of the approaches above worked for me. I solved this issue from the template side, finally.

  • There is a ticket filed (http://code.djangoproject.com/ticket/10427), which adds a "value" option to a template variable for a form. For instance, it allows,

{{form.locid.value}}

{{form.locid.value}}

被显示。这可以作为补丁来使用,可以使用patch -p0 file.patch安装在SVN版本的django中。

to be shown. This is available as a patch, which can be installed in the SVN version of django using "patch -p0 file.patch"


  • 请记住,{{form.locid.value}}变量将使用结合与不可见表单 - 否则,表单集的提交和保存操作将崩溃。

  • Remember, the {{form.locid.value}} variable will be used in conjunction with the invisible form - otherwise, the submit and save operations for the formset will crash.

这是与{{form.locid.data}}相同的,如上述票证中所述。

This is Not the same as {{form.locid.data}} - as is explained in the ticket referred to above.

这篇关于如何在django formset中显示隐藏的autofield的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆