关于 Django 中表单格式的简单问题
我想制作一个表单,让用户输入杂货清单。每个项目都由名称、金额和类别定义。我目前正在使用表单集执行此操作。这是我在views.py 文件中创建表单集实例的代码:
class InputForm(forms.Form):
item = forms.CharField()
amount = forms.CharField()
category = forms.CharField()
但这会产生如下所示的输出:
Item:
Amount:
Category:
Item:
Amount:
Category:
如何格式化输出以使“项目、金额、类别”序列变为水平?
Item: [room for user input] Amount: [user input] Category: [user selection]
Item: [room for user input] Amount: [user input] Category: [user selection]
我是否必须在模板中工作,或者我可以在 forms.py 文件中执行某些操作吗?
I'd like to produce a form that lets users input a list of grocery items. Each item is defined by a name, amount, and category. I'm currently doing this using formsets. Here's the code from which I create a formset instance in my views.py file:
class InputForm(forms.Form):
item = forms.CharField()
amount = forms.CharField()
category = forms.CharField()
But this produces an output that looks like this:
Item:
Amount:
Category:
Item:
Amount:
Category:
How can I format the output so that the "item, amount, category" sequence becomes horizontal?
Item: [room for user input] Amount: [user input] Category: [user selection]
Item: [room for user input] Amount: [user input] Category: [user selection]
Do I have to work within the template, or can I do something within my forms.py file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您有两种选择:
(1) 迭代模板中的表单集,并使用模板来布局表单;或
(2) 重写 Form 中的布局方法以更改生成的 html 布局。
我更喜欢(2),但很多人更喜欢(1)。 (2) 的优点是,如果将布局代码分解为 mixin,则可以重用该布局代码。 (我实际上已经通过猴子修补实现了这一点,但这是不必要的)。
You have two options:
(1) Iterate over the formset in your template, and use your template to layout the forms; or
(2) Override the layout methods in Form to alter the html layout that is generated.
I prefer (2), but plenty of people prefer (1). The advantage of (2) is that you can reuse that layout code if you break it out into a mixin. (I have actually achieved this with monkey-patching, but that is unnecessary).