gpt4 book ai didi

python - 在 Django 表单字段之间显示一些自由文本

转载 作者:太空狗 更新时间:2023-10-29 17:39:14 24 4
gpt4 key购买 nike

我有如下表格:

class MyForm(Form):

#personal data
firstname = CharField()
lastname = CharField()

#education data
university = CharField()
major = CharField()

#foobar data
foobar = ChoiceField()

由于某些字段(如 foobar)是从数据库中填充的,所以我不能使用其他方法,只能让 Django 使用 form.as_ul 为我呈现它

我也希望我不必为了便于维护而将表单拆分为多个表单

有没有办法告诉 Django 在这些表单部分之间显示帮助文本,以便我可以输入一些有关如何填写表单的说明?

我希望表单呈现如下内容:

<form>

<p>Here you enter your personal data...</p>
<input name='firstname'>
<input name='lastname'>

<p>Here you enter your education data...</p>
<input name='university'>
<input name='major'>

</form>

我是否需要创建自己的小部件才能显示这些 <P>标签,还是有更简单的方法?

谢谢

最佳答案

一种不使用 form.as_ul 在模板中显示表单的方法是使用 django-uni-form。首先你必须下载它here并安装它。然后用于设置表单的代码可能如下所示:

from uni_form.helpers import FormHelper, Submit, Layout, Fieldset

class MyForm(Form):

#personal data
firstname = CharField()
lastname = CharField()

#education data
university = CharField()
major = CharField()

#foobar data
foobar = ChoiceField()

# now attach a uni_form helper to display the form
helper = FormHelper()

# create the layout
layout = Layout(
# first fieldset
Fieldset("Here you enter your personal data...",
'firstname', 'lastname'),
Fieldset("Here you enter your education data...",
'university', 'major'),
Fieldset('foobar')

# and add a submit button
sumbit = Submit('add', 'Submit information')
helper.add_input(submit)

现在,要在您的模板中显示它,您可以这样做:

{% load uni_form %}
{% with form.helper as helper %}
{% uni_form form helper %}
{% endwith %}

这将输出 HTML(大致)如下:

<form>
<fieldset><legend>Here you enter your personal data...</legend>
<input name='firstname'>
<input name='lastname'>
</fieldset>

<fieldset><legend>Here you enter your education data...</legend>
<input name='university'>
<input name='major'>
</fieldset>

<fieldset>
<input name='foobar'>
</fieldset>

</form>

有关 uni_form 的更多信息,请阅读他们的文档(参见上面的链接)。

PS:我知道这个回复晚了,我相信你已经解决了这个问题,但我认为这对现在遇到这个问题的任何人都应该有所帮助。

关于python - 在 Django 表单字段之间显示一些自由文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/727917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com