使用Django Forms来显示和编辑? [英] Using Django Forms to display and edit?

查看:102
本文介绍了使用Django Forms来显示和编辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在摔跤如何在Django中最好地创建可用于显示或编辑数据的HTML页面。也就是说,我希望字段的值在显示模式下显示为文本,但在编辑/添加模式时,会在其小部件中显示。看来,Django并不是为了这样做:字段总是出现在他们的小部件中(例如,文本输入,文本区域,
等等)。



有没有一个常见的技术来处理这个问题,而不是使用一个表单,而不是其他的表单?



我在想一个可以用于每一个的自定义模板标签过滤器表单字段,如:



{{form.field_name | render_field:mode}}



其中,render_field将返回字段的HTML小部件,或者只是基于模式的文本值。



我错过了一些东西,还是这个可行的解决方案? b $ b

解决方案

显然我回答了我自己的问题。我结束了一个三部分的解决方案:


  1. 将模型附加到表单,所以我将为每个字段

  2. 使用模板标签编写表单,传递form.field,user和action

  3. 编写一个渲染模板标签来处理# 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:

  1. attach the model to the form, so I'll have the default display widgets for each field
  2. write the form using a template tag, passing it the form.field, user, and action
  3. 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屋!

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