Using Django Forms to display and edit?

前端 未结 4 568
天命终不由人
天命终不由人 2021-02-09 01:36

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 d

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-09 02:29

    I have the same problem. Right now I have separate templates for display and editing; the former renders object fields, the latter form fields (but sometimes also object fields, for things which are not editable). The HTML structure can be quite complex: for example, on some pages I have large tables representing a multi-level hierarchy of objects. As a result, I end up with a large amount of duplicated code in the two templates, which is the opposite of DRY.

    I have used template filters with form fields before, to save code when displaying errors together with the field. I think it would be a viable solution in this case. Another possibility may be to use a ModelForm subclass which can be told to render uneditable versions of the fields. This would help keep the templates simple. You could even render both the static and the editable version of a field, and use JavaScript to switch between them, activating and deactivating an editing mode.

提交回复
热议问题