在django中构建动态表单 [英] building dynamic forms in django

查看:116
本文介绍了在django中构建动态表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在根据存储在数据库中的字段及其定义动态构建表单。在我的数据库中,我已经定义了一个带有一些标签的复选框和一个带有一些标签的文本框。

I'm trying to build a form dynamically based on the field and its definitions stored in a database. In my db, I have defined 1 checkbox with some label and 1 textfield with some label.

如何从数据库中的数据在动态地构建表单?

How do I build a form dynamically in my view from the data in the db?

谢谢


Thanks

推荐答案

Django在您的模型定义

Django does a great job auto-generating forms from your model definitions.

第一步可能是创建一个反映现有数据库的Django模型。

The first step might be to create a Django model that mirrors your existing database.

关于复选框/文本框的东西:

Regarding the checkbox/textfield stuff:

Django有字段小部件之间的很大分隔。您可能有一个 IntegerField 存储数字,但是当您想要编辑该数字时,您可以更改显示给用户的小部件。在某些情况下,您可能会有一个输入框,另外一个是textarea,也可能是一个下拉列表。 字段将处理类型转换和验证等细节,窗口小部件决定表单字段的外观。

Django has a great separation between fields and widgets. You may have a IntegerField that stores numbers, but you can vary the widget that is displayed to the user when they want to edit that number. In some cases you might have an input box, in others a textarea, or perhaps a dropdown. The field will take care of details such as type conversion and validation, the widget determines what the form field looks like.

某些字段类型与他们关联的默认小部件,但您可以覆盖它们。

Certain field types have default widgets associated with them, but you can override them.

另外,请注意,表单域之间 strong>和模型字段

Also, note that there is a difference between form fields and model fields.

要动态执行,可以向自己添加项目.fields SortedDict在飞行中。 IE:

To do it dynamically, can add items to the self.fields SortedDict on the fly. I.E:

from django.forms.forms import Form
from django.forms.fields import CharField
class FunkyForm(Form):
    def __init__(self, *args, **kwargs):
        super(FunkyForm, self).__init__(*args, **kwargs)
        for item in range(5):
            self.fields['test_field_%s' % item] = CharField(max_length=255)

将为您提供一个使用5个动态生成的CharField实例化的表单类。

Will give a you a form class that instantiates with 5 dynamically generated CharFields.

这篇关于在django中构建动态表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆