使用视图中数据库中的数据填充 django 表单
我的 forms.py 中有一个表单,如下所示:
from django import forms
class ItemList(forms.Form):
item_list = forms.ChoiceField()
我需要使用数据库中的一些数据填充 item_list 。当在 HTML item_list 中生成时,应该类似于:
<select title="ItemList">
<option value="1">Select Item 1</option>
<option value="2">Select Item 2</option>
</select>
我的 select 语句中的选项值几乎每次都会更改,因为查询中的变量经常会更改生成新结果。
我需要在 view.py 和模板文件中添加哪些内容才能使用数据库中的值填充 ItemList?
I have a form in my forms.py that looks like this:
from django import forms
class ItemList(forms.Form):
item_list = forms.ChoiceField()
I need to populate the item_list with some data from the database. When generated in HTML item_list should be something like:
<select title="ItemList">
<option value="1">Select Item 1</option>
<option value="2">Select Item 2</option>
</select>
The options values in my select statement will change almost every time since a variable in the query will often change generating new results.
What do I need to put in the view.py and also in my template files to populate the ItemList with values from the database?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看一下 Django 文档中的这个示例:
基本上,您可以在 Field 对象上使用
queryset
关键字参数,从数据库中获取行:更新
如果您需要动态模型选择字段,您可以在表单的构造函数中移交项目 ID 并相应地调整查询集:
PS 我还没有测试过这个代码,我不确定你的确切设置,但我希望主要思想能够得到体现。
资源:
Take a look at this example in the Django documentation:
Basically, you can use the
queryset
keyword argument on a Field object, to grab rows from your database:Update
If you need a dynamic model choice field, you can hand over your item id in the constructor of the form and adjust the queryset accordingly:
P.S. I haven't tested this code and I'm not sure about your exact setup, but I hope the main idea comes across.
Resources:
你需要做的是找出你真正想要的对象,例如,如果你想找到一本名为“Upvote-if-u-like!”的书。那么你的 urls.py 应该像
现在一样,当有人搜索 mybook.com/textshare/upvote-if-u-like!/ 时
,他/她会被带到views.py,这看起来就像
bookForm 在 Models.py 中的位置, bookModelForm 在 forms.py 中
快乐的姜戈:)
What you need to do is to find out which object do you actually want for e.g. if you want to find out a book named "Upvote-if-u-like!" then your urls.py should like
now when someone will search for mybook.com/textshare/upvote-if-u-like!/
it will take him/her to views.py which would look like
where bookForm is in Models.py and bookModelForm is in forms.py
Happy Djangoing:)