如何在 django 表单集中显示隐藏的自动字段

发布于 2024-07-20 06:11:54 字数 1518 浏览 9 评论 0原文

使用表单集显示时,Django 自动字段默认是隐藏的。 展示它的最佳方式是什么?

目前,该模型被声明为,

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

当使用 Django 表单集呈现时,

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

它在页面上显示为,

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

谢谢。


编辑

我创建这样的表单集 -

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

第二次编辑

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

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

目前,我可以从 BaseModelFormSet 类继承并使用自定义查询集,或者我可以使用 ModelForm 类将自定义字段添加到表单。 有没有办法用表单集来完成这两项工作?


第三次编辑

我现在正在使用,

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
  • 使用指定的自定义查询。

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)
   ...

When this is rendered using Django formsets,

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

it shows up on the page as,

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

Thanks.


Edit

I create the formset like this -

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

Second Edit

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

How would I create a formset from a custom form (which will show a hidden field), as well as use a custom queryset?

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?


Third Edit

I'm now using,

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()

But this still doesn't

  • Show locid
  • Use the custom query that was specified.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

情绪操控生活 2024-07-27 06:11:54

尝试更改默认字段类型:

from django import forms
class MyModelForm(ModelForm):
  locid = forms.IntegerField(min_value=1, required=True)
  class Meta:
    model = MyModel
    fields = ('locid', 'name')

编辑:已测试且有效...

Try changing the default field type:

from django import forms
class MyModelForm(ModelForm):
  locid = forms.IntegerField(min_value=1, required=True)
  class Meta:
    model = MyModel
    fields = ('locid', 'name')

EDIT: Tested and works...

Smile简单爱 2024-07-27 06:11:54

正如您所说,您没有使用您定义的自定义表单。 这是因为你没有将它传递到任何地方,所以 Django 无法知道它。

解决方案很简单 - 只需将自定义表单类传递到 modelformset_factory:

LocFormSet = modelformset_factory(MyModel, form=MyModelForm) 

Edit 以响应更新 3:

首先,您在错误的位置重新定义了 locid - 它需要在类级别,不在 __init__ 内。

其次,将查询集放入表单中根本不会执行任何操作 - 表单不了解查询集。 您应该回到之前所做的事情,在实例化表单集时将其作为参数传递。 (或者,您可以定义一个自定义表单集,但这似乎有点过头了。)

class MyModelForm(ModelForm):
    locid = forms.IntegerField(min_value=1, required=True)

    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['locid'].widget.attrs["type"] = 'visible'
    class Meta:
        model = MyModel
        fields = ('locid', 'name')

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

As you say, you are not using the custom form you have defined. This is because you aren't passing it in anywhere, so Django can't know about it.

The solution is simple - just pass the custom form class into modelformset_factory:

LocFormSet = modelformset_factory(MyModel, form=MyModelForm) 

Edit in response to update 3:

Firstly, you have the redefinition for locid in the wrong place - it needs to be at the class level, not inside the __init__.

Secondly, putting the queryset inside the form won't do anything at all - forms don't know about querysets. You should go back to what you were doing before, passing it in as a parameter when you instantiate the formset. (Alternatively, you could define a custom formset, but that seems like overkill.)

class MyModelForm(ModelForm):
    locid = forms.IntegerField(min_value=1, required=True)

    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['locid'].widget.attrs["type"] = 'visible'
    class Meta:
        model = MyModel
        fields = ('locid', 'name')

LocFormSet = modelformset_factory(MyModel, form = MyModelForm)
pformset = LocFormSet(request.POST, request.FILES,
                      queryset=MyModel.objects.order_by('name')))
夏了南城 2024-07-27 06:11:54

好吧,上面的方法都不适合我。 我终于从模板方面解决了这个问题。

显示 。 这是一个补丁,可以使用“patch -p0 file.patch”安装在 SVN 版本的 django 中

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

  • 与 {{form.locid.data}} 相同 - 正如上面提到的票证中所解释的。

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

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

  • 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.

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

命比纸薄 2024-07-27 06:11:54

自动字段被隐藏的原因是 BaseModelFormSet 和 BaseInlineFormSet 都覆盖了 add_field 中的该字段。 修复它的方法是创建自己的表单集并覆盖 add_field 而不调用 super。 此外,您不必显式定义主键。

您必须将表单集传递给 modelformset_factory:

    LocFormSet = modelformset_factory(MyModel, 
           formset=VisiblePrimaryKeyFormSet)

这是在表单集类中:

from django.forms.models import BaseInlineFormSet, BaseModelFormSet, IntegerField
from django.forms.formsets import BaseFormSet

class VisiblePrimaryKeyFormset(BaseModelFormSet):
    def add_fields(self, form, index):
        self._pk_field = pk = self.model._meta.pk
        if form.is_bound:
            pk_value = form.instance.pk
        else:
            try:
                pk_value = self.get_queryset()[index].pk
            except IndexError:
                pk_value = None
        form.fields[self._pk_field.name] = IntegerField( initial=pk_value,
                 required=True) #or any other field you would like to display the pk in
        BaseFormSet.add_fields(self, form, index) # call baseformset which does not modify your primary key field

The reason that the autofield is hidden, is that both BaseModelFormSet and BaseInlineFormSet override that field in add_field. The way to fix it is to create your own formset and override add_field without calling super. Also you don't have to explicitly define the primary key.

you have to pass the formset to modelformset_factory:

    LocFormSet = modelformset_factory(MyModel, 
           formset=VisiblePrimaryKeyFormSet)

This is in the formset class:

from django.forms.models import BaseInlineFormSet, BaseModelFormSet, IntegerField
from django.forms.formsets import BaseFormSet

class VisiblePrimaryKeyFormset(BaseModelFormSet):
    def add_fields(self, form, index):
        self._pk_field = pk = self.model._meta.pk
        if form.is_bound:
            pk_value = form.instance.pk
        else:
            try:
                pk_value = self.get_queryset()[index].pk
            except IndexError:
                pk_value = None
        form.fields[self._pk_field.name] = IntegerField( initial=pk_value,
                 required=True) #or any other field you would like to display the pk in
        BaseFormSet.add_fields(self, form, index) # call baseformset which does not modify your primary key field
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文