Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Django Forms to display and edit?

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?

like image 961
Doug Blank Avatar asked Dec 15 '09 12:12

Doug Blank


People also ask

How do I edit a form in Django?

Create Formfrom . models import Post : load(import) Post Model that we'll add or edit the data via Form. class Meta: : write contents which we want to use via this Form. in here, we set we'll use Post Model in this form( model = Post ), and we'll use title and content fields( fields = ('title', 'content') ).

What is Django crispy forms?

Django-crispy-forms is an application that helps to manage Django forms. It allows adjusting forms' properties (such as method, send button or CSS classes) on the backend without having to re-write them in the template.

What is the difference between forms and model forms in Django?

The similarities are that they both generate sets of form inputs using widgets, and both validate data sent by the browser. The differences are that ModelForm gets its field definition from a specified model class, and also has methods that deal with saving of the underlying model to the database. Save this answer.


1 Answers

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
like image 74
Doug Blank Avatar answered Oct 13 '22 16:10

Doug Blank