Login

ReadOnlyFieldsMixin to Form, ModelForm and Views (helper function)

Author:
luzfcb
Posted:
July 15, 2015
Language:
Python
Version:
1.7
Score:
0 (after 0 ratings)

Usage:

class Foo(models.Model):
    description = models.TextField()
    number = models.IntegerField()


class FooOnlyDescriptionIsReadOnly(ReadOnlyFieldsMixin, forms.ModelForm):
    readonly_fields = ('description', )
    class Meta:
        model = Foo
        fields = '__all__'

class FooAllFieldsIsReadOnly(ReadOnlyFieldsMixin, forms.ModelForm):
    class Meta:
        model = Foo
        fields = '__all__'

or use the function

class FooForm(forms.ModelForm):
    class Meta:
        model = Foo
        fields = '__all__'

ReadOnlyFooForm = new_readonly_form_class(FooForm, readonly_fields=('description', ))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from __future__ import unicode_literals
# created by Edgar Gabaldi https://github.com/edgabaldi
# and Fabio C. Barrionuevo da Luz https://github.com/luzfcb


from django.utils import six
from django.utils.encoding import force_str

__all__ = (
    'ReadOnlyFieldsMixin',
    'new_readonly_form_class'
)


class ReadOnlyFieldsMixin(object):
    """Usage:
    
    class MyFormAllFieldsReadOnly(ReadOnlyFieldsMixin, forms.Form):
        ...
        
        
    class MyFormSelectedFieldsReadOnly(ReadOnlyFieldsMixin, forms.Form):
        readonly_fields = ('field1', 'field2')
        ...
    """
    readonly_fields = ()

    def __init__(self, *args, **kwargs):
        super(ReadOnlyFieldsMixin, self).__init__(*args, **kwargs)
        self.define_readonly_fields(self.fields)

    def clean(self):
        cleaned_data = super(ReadOnlyFieldsMixin, self).clean()

        for field_name, field in six.iteritems(self.fields):
            if self._must_be_readonly(field_name):
                cleaned_data[field_name] = getattr(self.instance, field_name)

        return cleaned_data

    def define_readonly_fields(self, field_list):

        fields = [field for field_name, field in six.iteritems(field_list)
                  if self._must_be_readonly(field_name)]

        map(lambda field: self._set_readonly(field), fields)

    def _all_fields(self):
        return not bool(self.readonly_fields)

    def _set_readonly(self, field):
        field.widget.attrs['disabled'] = 'true'
        field.required = False

    def _must_be_readonly(self, field_name):
        return field_name in self.readonly_fields or self._all_fields()


def new_readonly_form_class(form_class, readonly_fields=()):
    name = force_str("ReadOnly{}".format(form_class.__name__))
    class_fields = {'readonly_fields': readonly_fields}
    return type(name, (ReadOnlyFieldsMixin, form_class), class_fields)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 3 weeks ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.