使用Django Forms来显示和编辑? [英] Using Django Forms to display and edit?
问题描述
等等)。
有没有一个常见的技术来处理这个问题,而不是使用一个表单,而不是其他的表单?
我在想一个可以用于每一个的自定义模板标签过滤器表单字段,如:
{{form.field_name | render_field:mode}}
其中,render_field将返回字段的HTML小部件,或者只是基于模式的文本值。
我错过了一些东西,还是这个可行的解决方案? b $ b
显然我回答了我自己的问题。我结束了一个三部分的解决方案:
- 将模型附加到表单,所以我将为每个字段
- 使用模板标签编写表单,传递form.field,user和action
- 编写一个渲染模板标签来处理# 2
第一步:
form .model = Model(...)
第二步:
{{form.field1.label}}
{%render form.field1 user action%}
{{form.field2 .label}}
{%render form.field2 user action%}
第三步:
如下所示:
def render(formfield,user,action,default_text =Private ):
如果不是user.is_authenticated():
action =视图
如果action ==视图:
如果user.is_authenticated():
fieldname = formfield.name
retval = str(g etattr(formfield.form.model,fieldname))
else:
retval = default_text
else:
retval = formfield.as_widget()
return retval
I'm wrestling with how to best create HTML pages in Django that can either be used for displaying or editing data. That is, I'd like the field's values to appear as text in display mode, but in their widgets when in edit/add mode. It appears that Django wasn't designed to do this: the fields always appear in their widgets (eg, text input, text area, etc).
Is there a common technique for handling this, short of using forms for one, and not the other?
I was thinking of a custom templatetag filter that could be used for every form field, like:
{{ form.field_name|render_field:mode }}
where render_field would either return the field's HTML widget, or just the value as text, based on the mode.
Have I missed something, or is this a viable solution?
Answering my own question, apparently. I ended up with a three-part solution:
- attach the model to the form, so I'll have the default display widgets for each field
- write the form using a template tag, passing it the form.field, user, and action
- write a render template tag to handle #2
Step one:
form.model = Model(...)
Step two:
{{form.field1.label}} {% render form.field1 user action %} {{form.field2.label}} {% render form.field2 user action %}
Step three:
Something like:
def render(formfield, user, action, default_text="Private"): if not user.is_authenticated(): action = "view" if action == "view": if user.is_authenticated(): fieldname = formfield.name retval = str(getattr(formfield.form.model, fieldname)) else: retval = default_text else: retval = formfield.as_widget() return retval
这篇关于使用Django Forms来显示和编辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!