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?
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') ).
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.
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.
Answering my own question, apparently. I ended up with a three-part solution:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With