Using Django Forms to display and edit?

前端 未结 4 501
天命终不由人
天命终不由人 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:36

    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
    

提交回复
热议问题