在视图中使用数据库中的数据填充Django表单

编程入门 行业动态 更新时间:2024-10-24 12:30:06
本文介绍了在视图中使用数据库中的数据填充Django表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的form.py中有一个看起来像这样的表单:

I have a form in my forms.py that looks like this:

from django import forms class ItemList(forms.Form): item_list = forms.ChoiceField()

我需要用数据库中的一些数据填充item_list。在HTML中生成时,item_list应该类似于:

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>

我的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.

我需要在view.py和模板文件中放入哪些内容,以便使用数据库中的值填充ItemList?

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?

推荐答案

在Django文档中查看以下示例:

Take a look at this example in the Django documentation:

  • http:// docs.djangoproject/en/dev/topics/forms/modelforms/#a-full-example
  • docs.djangoproject/en/dev/topics/forms/modelforms/#a-full-example

,您可以在Field对象上使用 queryset 关键字参数,从数据库中获取行:

Basically, you can use the queryset keyword argument on a Field object, to grab rows from your database:

class BookForm(forms.Form): authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())

更新

如果需要一个动态模型选择字段,您可以将您的商品ID移交给表单的构造函数,并相应地调整查询集:

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:

class ItemForm(forms.Form): # here we use a dummy `queryset`, because ModelChoiceField # requires some queryset item_field = forms.ModelChoiceField(queryset=Item.objects.none()) def __init__(self, item_id): super(ItemForm, self).__init__() self.fields['item_field'].queryset = Item.objects.filter(id=item_id)

聚苯乙烯我尚未测试此代码,也不确定您的确切设置,但希望能理解主要思想。

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.

资源:

  • www.mail-archive/django-users@googlegroups/msg48058.html
  • docs.djangoproject/en/dev/ref/forms/fields/#django。 form.ModelChoiceField
  • www.mail-archive/django-users@googlegroups/msg48058.html
  • docs.djangoproject/en/dev/ref/forms/fields/#django.forms.ModelChoiceField

更多推荐

在视图中使用数据库中的数据填充Django表单

本文发布于:2023-08-05 20:52:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1307990.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   表单   数据库中   数据   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!