- Author:
- mkoistinen
- Posted:
- April 16, 2020
- Language:
- Python
- Version:
- Not specified
- Tags:
- forms select readonly
- Score:
- 0 (after 0 ratings)
A minimally invasive Select widget that looks and acts like a disabled select input, but still submits with the form. It works by rendering the form as disabled, and supplements it's output with a hidden input field with the same name and value.
Tested in Django 3.0, probably works in Django 1.11+
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | # common/fields.py
from django.forms import Select
class ReadOnlySelect(Select):
"""
A "Select" widget that presents as a disabled select input, but also
renders a hidden field with the field's name and selected value so that it
is represented in the submitted form.
"""
template_name = 'common/readonly_select.html'
def __init__(self, attrs=None, **kwargs):
if attrs is None:
attrs = {}
attrs.update({'disabled': True})
super().__init__(attrs=attrs, **kwargs)
# common/readonly_select.html
{% include 'django/forms/widgets/select.html' %}
<input type="hidden" name="{{ widget.name }}" value="{{ widget.value.0 }}">
|
More like this
- Serialize a model instance by chriswedgwood 1 week, 6 days ago
- Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 9 months, 2 weeks ago
- Crispy Form by sourabhsinha396 10 months, 1 week ago
- ReadOnlySelect by mkoistinen 10 months, 3 weeks ago
- Verify events sent to your webhook endpoints by santos22 11 months, 2 weeks ago
Comments
Please login first before commenting.