Задать вопрос

Тел: +7 965 3737 888





Readonly fields on Form/Modelform

<p>A Form and ModelForm which provides the ability to specify certain fields as readonly, meaning that they will display their value as text wrapped with a &lt;span&gt; tag. The user is unable to edit them, and they are protected from POST data insertion attacks.</p>
<p>The recommended usage is to place a NewMeta inner class on the form, with a readonly attribute which is a list or tuple of fields, similar to the fields and exclude attributes on the Meta inner class.</p>
class MyForm(ReadonlyForm):
    foo = forms.TextField()
    bar = forms.TextField()
    class NewMeta:
        readonly = ('foo',)

<p>Use these forms as you would a standard form in your templates.</p>

Вопрос полезен? Да0/Нет0

Ответы (5):

Ответ полезен? Да0/Нет0

This is not working at all for me. It works "fine" up until I try to save a modelform with some fields as read-only. Something in the system tries to verify the readonly fields and I am getting errors.

I'm new to django, and since no one else is complaining about this perhaps it's my code, but I can't figure it out.

Ответ полезен? Да0/Нет0


it works for me with dropdown lists and text fields.

how can I make it work with checkboxes?


Ответ полезен? Да0/Нет0

Old snippet I know, but I have a fix for most field types (actually all of the ones I've tested including foreign keys and choice fields).

Replace Line 14:

forms.util.flatatt(final_attrs), self.display_value))

Replace Line 48:

model_field = self.instance._meta.get_field_by_name(name)[0]
field.widget.original_value = model_field.value_from_object(self.instance)
field.widget.display_value = self.instance.get_field_display(name)

Ответ полезен? Да0/Нет0

It's even a bit trickier than that; this won't work with initial data, either; you have to actually populate the form with data for this to work.

Ответ полезен? Да0/Нет0

This doesn't work at all, at least not the base Readonly object, without a ModelForm.

The base Form class doesn't have an 'instance' property.