使用数据库数据填充 Django 表单字段数据
我正在尝试使用 Db 对象中的数据预填充表单字段。如何设置表单、视图和模型来使用这些数据填充字段?
目标是让用户仅选择从对象中查询的数据。前任。活动中有乐队演奏,用户从活动中选择他们最喜欢的乐队。
我尝试查看 form.data 的文档 - 但似乎找不到我要找的东西。
谢谢!
I am trying pre-fill a form field with data from a Db object. How do you set up the form,view, and model to fill a field with this data?
The goal is to let the user only select data that is queried from the object. Ex. An event has bands playing, the user selects their favorite band from those at the event.
I tried looking through the docs for form.data - but can't seem to find what I'm looking for.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您的事件模型具有作为 Many-2-Many 键的 band,则表单和视图的布局将如下所示:
forms.py:
注意:您需要根据您的要求调整表单中的查询集获取。
views.py:
此外,根据 dcrodjer 给出的建议,继续阅读一些有关实现 ModelMultipleChoiceField
Supposing your Events model has bands as Many-2-Many key, the layout of the forms and views would be as follows:
forms.py:
NOTE: You would need to adjust the queryset fetching in the forms for your requirement.
views.py:
Moreover, in line with the suggestion given by dcrodjer, go ahead and read some text on implementing ModelMultipleChoiceField
Form then 来获得更多自定义功能
您可以通过将参数传递给视图中的
You can get a little more custom by passing arguments to the Form
Then in your views