Django 1.2:自定义表单字段?
我有一个动态表单,其中包含一个或多个 MultipleChoiceFields 或 ChoiceFields。我想向用户显示一条指令,例如对于 ChoiceField:“选择以下一项”,对于 MultipleChoiceField:“选择以下一项”
我该如何执行此操作?我尝试对每个字段进行子类化,但无法在模板中获取值。
谢谢
编辑
我尝试了类似的操作:
class MultiWithInstruction(forms.MultipleChoiceField):
def __init__(self, instruction=None, **kwargs):
self.instruction=instruction
return super(MultiWithInstruction, self).__init__(**kwargs)
我无法检索模板中“指令”的值。
I've got a dynamic form that contains either one or several MultipleChoiceFields or ChoiceFields. I want to display an instruction to the user, e.g. for ChoiceField: "Select one of the following", and for MultipleChoiceField: "Select any of the following"
How can I do this? I tried subclassing each of these fields, but I couldn't get the value back out in the template.
Thanks
EDIT
I tried something like:
class MultiWithInstruction(forms.MultipleChoiceField):
def __init__(self, instruction=None, **kwargs):
self.instruction=instruction
return super(MultiWithInstruction, self).__init__(**kwargs)
I couldn't retrieve the value of 'instruction' in the template.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不直接使用
help_text
?然后在模板中你可以做这样的事情:
Why not just use
help_text
?And then in the template you could do something like this:
您可以在表单字段中设置标签值:
You can set the label value in your form field:
我也有同样的问题。我找不到一个简单的方法(不重写 django.forms 中的很多东西),所以我想出了这个快速而肮脏的解决方案。
定义一个新的模板过滤器,将字符串拆分为列表,给定分隔符;请参阅 Ciantic 的这个简单的片段。将代码片段保存为
templatetags/whatever_name.py
。在
forms.py
中,使用帮助和说明字符串填充字段的help_text
属性,并用“#”分隔(当然,您可以选择所需的任何分隔符) ;像help_text
这样的东西是一个字符串(已标记为安全),因此您不能在其中放入列表(这就是需要自定义拆分过滤器的原因)。
这是一个模板示例,显示表单中每个字段的帮助和指令字符串:
显然,您不能使用
as_p
、as_table
和as_ul
来呈现表单。I had the same problem. I couldn't find an easy way (without overriding a lot of stuff from django.forms) so I came up with this quick-and-dirty solution.
Define a new template filter, that splits a string into a list, given a separator; see this simple snippet by Ciantic. Save the snippet as
templatetags/whatever_name.py
.In
forms.py
, fill thehelp_text
attribute of the field with your help and instruction strings, separated by '#' (you can choose whatever separator you want, of course); something likehelp_text
is a string (already marked safe), so you can't put a list in it (this is why the custom split filter is needed).And this is an example of a template that shows help and instruction strings for each field in the form:
Obviously, you can't use
as_p
,as_table
andas_ul
to render the form.