Login

django-constance generic view

Author:
skam
Posted:
February 9, 2015
Language:
Python
Version:
1.7
Score:
0 (after 0 ratings)

For several projects I am using generic views instead of django-admin, I needed a generic view for constance instead of using their django-admin based app.

 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
from operator import itemgetter

from django.utils.formats import localize
from django.views.generic.edit import FormView
from django.utils.translation import ugettext_lazy as _

from constance import settings, LazyConfig
from constance.admin import ConstanceForm


config = LazyConfig()


class ConstanceConfigView(FormView):
    form_class = ConstanceForm
    template_name = 'dashboard/constance/config.html'

    def __init__(self, *args, **kwargs):
        if 'fields' in kwargs:
            self.fields = kwargs.pop('fields')
        else:
            self.fields = settings.CONFIG.keys()
        super(ConstanceConfigView, self).__init__(*args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ConstanceConfigView, self).get_context_data(**kwargs)
        context['config'] = []
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        initial = self.get_initial()
        for name, (default, help_text) in settings.CONFIG.items():
            value = initial.get(name)
            if value is None:
                value = getattr(config, name)
            context['config'].append({
                'name': name,
                'default': localize(default),
                'help_text': _(help_text),
                'value': localize(value),
                'modified': value != default,
                'form_field': form[name],
            })
        context['config'].sort(key=itemgetter('name'))
        return context

    def get_initial(self):
        data = super(ConstanceConfigView, self).get_initial()
        default_initial = ((name, default) for name, (default, help_text) in settings.CONFIG.items() if name in self.fields)
        initial = dict(default_initial, **dict(config._backend.mget([k for k in settings.CONFIG.keys() if k in self.fields])))
        data.update(initial)
        return data

    def form_valid(self, form):
        form.save()
        return super(ConstanceConfigView, self).form_valid(form)

More like this

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

Comments

Please login first before commenting.