从模型表单创建模型表单集

发布于 2024-07-20 21:36:52 字数 949 浏览 7 评论 0原文

我有一个模型 MyModel,其中包含 PK - locid,即 AutoField。

我想由此构造一个模型表单集,但有一些警告:

  • 表单集的查询集应该是自定义的(例如 order_by('field'))而不是 all()
  • 因为 MyModel 的 locid 是一个 AutoField,因此被隐藏默认情况下,我希望能够将其显示给用户。

我不知道该怎么做。 我尝试了多种方法,

MyModelFormSet = modelformset_factory(MyModel, fields=('locid', 'name', 'dupof'))

上面给了我 3 个字段,但 locid 被隐藏了。

class MyModelForm(ModelForm):

  def __init__(self, *args, **kwargs):
    super(MyModelForm, self).__init__(*args, **kwargs)
    self.fields['locid'].widget.attrs["type"] = 'visible'
    locid = forms.IntegerField(min_value = 1, required=True)

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

上面给了我一个 ManyToMany 错误。

以前有人做过这样的事情吗?


编辑2

我现在可以在实例化表单集时使用自定义查询 - 但我仍然需要向用户显示 locid 字段,因为 id 对于应用程序的使用很重要。 我该怎么做? 如果是自动字段,是否有办法覆盖隐藏 PK 的默认行为?

I have a model MyModel which contains a PK - locid, that is an AutoField.

I want to construct a model formset from this, with some caveats:

  • The queryset for the formset should be a custom one (say, order_by('field')) rather than all()
  • Since locid for MyModel is an AutoField and thus hidden by default, I want to be able to show it to the user.

I'm not sure how to do this. I've tried multiple approaches,

MyModelFormSet = modelformset_factory(MyModel, fields=('locid', 'name', 'dupof'))

The above gives me the 3 fields, but locid is hidden.

class MyModelForm(ModelForm):

  def __init__(self, *args, **kwargs):
    super(MyModelForm, self).__init__(*args, **kwargs)
    self.fields['locid'].widget.attrs["type"] = 'visible'
    locid = forms.IntegerField(min_value = 1, required=True)

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

The above gives me a ManyToMany error.

Has anyone done something like this before?


Edit 2

I can now use a custom query when I instantiate the formset - but I still need to show the locid field to the user, because the id is important for the application's use. How would I do this? Is there a way to override the default behavior of hiding a PK if its an autofield?

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

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

发布评论

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

评论(3

旧人 2024-07-27 21:36:52

向用户显示自动字段是没有意义的,因为它是一个自动增量主键——用户无法更改它,并且在将记录保存到数据库之前(DBMS 选择下一个可用的 id),它不可用。

这是为表单集设置自定义查询集的方法:

from django.forms.models import BaseModelFormSet

class OrderedFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        self.queryset = MyModel.objects.order_by("field")
        super(OrderedFormSet, self).__init__(*args, **kwargs)

然后在工厂函数中使用该表单集:

MyModelFormSet = modelformset_factory(MyModel, formset=OrderedFormSet)

It makes no sense to show an autofield to the user, as it's an autoincremented primary key -- the user can not change it and it will not be available before saving the record to the database (where the DBMS selectes the next available id).

This is how you set a custom queryset for a formset:

from django.forms.models import BaseModelFormSet

class OrderedFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        self.queryset = MyModel.objects.order_by("field")
        super(OrderedFormSet, self).__init__(*args, **kwargs)

and then you use that formset in the factory function:

MyModelFormSet = modelformset_factory(MyModel, formset=OrderedFormSet)
好听的两个字的网名 2024-07-27 21:36:52

我最终使用模板侧变量来执行此操作,正如我在这里提到的:

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

I ended up using a template side variable to do this, as I mentioned here:

How to show hidden autofield in django formset

笨笨の傻瓜 2024-07-27 21:36:52

如果您喜欢廉价的解决方法,为什么不将 locid 修改为 __unicode__ 方法呢? 保证用户能够看到它,并且不需要 django-admin 的特殊知识。

但是,公平地说,我对 django-admin 相关问题的所有回答都倾向于“不要竭力使 django-admin 成为通用 CRUD 界面”。

If you like cheap workarounds, why not mangle the locid into the __unicode__ method? The user is guaranteed to see it, and no special knowledge of django-admin is required.

But, to be fair, all my answers to django-admin related questions tend along the lines of "don't strain to hard to make django-admin into an all-purpose CRUD interface".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文