Django formset 设置自定义参数的用处是什么?

huangapple go评论48阅读模式
英文:

What is the usefulness of setting custom parameters to Django formset

问题

我在阅读关于表单和表单集的文件时,遇到了自定义表单集和表单的__init__参数。我对概念有点了解,但不知道如何在实际生活中设置自定义参数的应用。请有人为我详细解释一下。

我尝试查看一些关于在Stack Overflow上传递自定义参数给表单和表单集的问题,我了解了概念,但不知道将自定义参数传递给表单和表单集的实际应用。

英文:

I was reading through the documents on forms and formset when I came across customizing formset and form's init parameters. I quiet get the concept but I don't know any real life application of setting a custom parameters. Someone please broaden this for me.

I tried looking into some questions asked concerning custom parameters here on Stack overflow, I get the concept but I don't know any real application of passing custom parameters to forms and formsets

答案1

得分: 1

想象一个游戏,玩家可以选择攻击他的邻居。显然,每个玩家的邻居都不同。每个邻居也是一个玩家。对于攻击移动,玩家需要从这四个邻居中选择一个。

基本上,你的表单需要一个动态的ModelChoiceField。动态意味着每个玩家的邻居都不同。

英文:

Imagine a game where a player can choose to attack his neighbors. Obviously every player has different neighbors. Every neighbor is also a player. For the attack-move the player needs to choose one neighbor out of these four.

Basically your form needs a dynamic ModelChoiceField. Dynamic hence every player has different neighbors.

class AttackForm(forms.Form, BaseForm):

    def __init__(self, neighbor_queryset, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['neighbors'] = forms.ModelChoiceField(
            queryset=neighbor_queryset,
            widget=forms.Select()
        )

This allows you to pass the neighbor_queryset on the fly to the form. See another example for ModelChoiceField (here). They did not explicitly put queryset in the arguments of __init__, therefore you have to pop() it from the kwargs.

huangapple
  • 本文由 发表于 2023年3月20日 22:57:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75791887.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定