Login

ReadOnlySelect

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

  1. Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 5 months ago
  2. Crispy Form by sourabhsinha396 6 months ago
  3. ReadOnlySelect by mkoistinen 6 months, 1 week ago
  4. Verify events sent to your webhook endpoints by santos22 7 months, 1 week ago
  5. Django Language Middleware by agusmakmun 7 months, 3 weeks ago

Comments

Please login first before commenting.