Login

ReadOnlySelect

Author:
mkoistinen
Posted:
April 16, 2020
Language:
Python
Version:
Not specified
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. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.