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

Тел: +7 965 3737 888

454

Просмотров

5

Ответов

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
file_4902.py(3.1Кб)
None

Ответы (5):

Ответjamida:24.05.2010
Ответ полезен? Да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.

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

Hi,

it works for me with dropdown lists and text fields.

how can I make it work with checkboxes?

Thanks.

Ответperrigo:26.10.2011
Ответ полезен? Да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)

Ответoffby1:28.02.2011
Ответ полезен? Да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.

Ответoffby1:17.08.2010
Ответ полезен? Да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.