扩展 django 表单

发布于 2024-11-09 04:58:24 字数 437 浏览 0 评论 0原文

我有一个模型表单,其中包含三个必填字段:usernetworkpositionpositionrequest.POST 拉取,另外两个将在其外部提供。这就是我目前所拥有的:

form = StartForm(request.POST)
form.save()

显然,此表单未验证,因为我尚未提供 usernetwork 实例。如何将这些附加信息添加到表单中?从概念上讲,我正在寻找这样的东西:

form = StartForm(request.POST + user_id=10, network_id=20)
form.save()

I have a modelform, which has three required fields: user, network, and position. The position is pulled by request.POST, and the other two will be supplied outside of it. This is what I currently have:

form = StartForm(request.POST)
form.save()

Obviously, this form is not validating, because I haven't provided the user and network instances. How do I add this additional information to the form? Conceptually, I'm looking for something like this:

form = StartForm(request.POST + user_id=10, network_id=20)
form.save()

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

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

发布评论

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

评论(2

还不是爱你 2024-11-16 04:58:24

您不能执行类似以下操作:form = StartForm(position = request.POST, user_id = 10, network_id = 20)吗?您可能必须打印 request.POST 的值,因为我认为它实际上是一个列表。所以只需找出 request.POST 中的位置即可

Can't you do something similar to: form = StartForm(position = request.POST, user_id = 10, network_id = 20)? You might have to print the value for request.POST since I think it's actually a list. So just find out what position is in the request.POST

_失温 2024-11-16 04:58:24

有两个选项:

  1. usernetwork 字段不允许来自 request.POST。例如,如果 user 应该是来自 request.user 的当前登录用户。

    在这种情况下你可以这样做:

    class StartForm(form.models.ModelForm):
    
        类元:
            模型=我的模型
            fields = ["position", ] # 表单中不包含用户和网络
    
    表单= StartForm(请求.POST,实例= MyModel(用户=用户,网络=网络))
    

    因此,您使用具有预填充字段的模型来初始化表单。

  2. usernetwork 字段允许来自 request.POST。然后你就可以:

    form = StartForm(request.POST, initial={"user": 用户, "network": 网络})
    

    请注意,在这种情况下,usernetwork 字段可能会被来自 request.POST 的值覆盖。

There are two options there:

  1. user and network fields are not allowed to come from request.POST. For example if user should be the currently logged in user which comes from request.user.

    In that case you can do:

    class StartForm(form.models.ModelForm):
    
        class Meta:
            model = MyModel
            fields = ["position", ] # You don't include user and network to the form
    
    form = StartForm(request.POST, instance=MyModel(user=user, network=network))
    

    So you initialize the form with a model which has pre-filled fields.

  2. user and network fields are allowed to come from request.POST. Then you do:

    form = StartForm(request.POST, initial={"user": user, "network": network})
    

    Note that in this case user and network fields may be overriden by values which come from request.POST.

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