扩展 django 表单
我有一个模型表单,其中包含三个必填字段:user
、network
和 position
。 position
由 request.POST
拉取,另外两个将在其外部提供。这就是我目前所拥有的:
form = StartForm(request.POST)
form.save()
显然,此表单未验证,因为我尚未提供 user
和 network
实例。如何将这些附加信息添加到表单中?从概念上讲,我正在寻找这样的东西:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能执行类似以下操作:
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有两个选项:
user
和network
字段不允许来自request.POST
。例如,如果user
应该是来自request.user
的当前登录用户。在这种情况下你可以这样做:
因此,您使用具有预填充字段的模型来初始化表单。
user
和network
字段允许来自request.POST
。然后你就可以:请注意,在这种情况下,
user
和network
字段可能会被来自request.POST
的值覆盖。There are two options there:
user
andnetwork
fields are not allowed to come fromrequest.POST
. For example ifuser
should be the currently logged in user which comes fromrequest.user
.In that case you can do:
So you initialize the form with a model which has pre-filled fields.
user
andnetwork
fields are allowed to come fromrequest.POST
. Then you do:Note that in this case
user
andnetwork
fields may be overriden by values which come fromrequest.POST
.