Login

ModelValue for djagno-livesettings

Author:
kmmbvnr
Posted:
September 9, 2010
Language:
Python
Version:
1.2
Score:
1 (after 1 ratings)

Extension for django-livesettings project - http://bitbucket.org/bkroeze/django-livesettings/

Allow to specify the model instance in settings

Usage:

config_register(
    ModelValue(BASE_GROUP, 'TestValue', 
        queryset = Value.objects.all(), 
        required=False)
 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
# -*- coding: utf-8 -*-
from django import forms
from livesettings import Value, IntegerValue
from livesettings.values import NOTSET

class ModelValue(Value):
    def __init__(self, group, key, queryset, **kwargs):
        self.empty_label = kwargs.pop('empty_label', '-----------')
        self.required = kwargs.pop('required', True)
        self.queryset = queryset
        super(ForeignKeyValue, self).__init__(group, key, **kwargs)

    @property
    def field(self):
        class field(forms.ModelChoiceField):
            def __init__(inst, **kwargs):
                import ipdb; ipdb.set_trace()
                forms.ModelChoiceField.__init__(
                    inst,
                    queryset=self.queryset, 
                    empty_label = self.empty_label,
                    required = self.required,
                    **kwargs)

        return field

    def choice_field(self, **kwargs):
        if self.hidden:
            kwargs['widget'] = forms.MultipleHiddenInput()
        return self.field(**kwargs)

    def to_python(self, value):
        if value == NOTSET:
            return None
        if isinstance(value, unicode) and value.isdigit():
            return self.queryset.get(pk=int(value))
        return value

    def to_editor(self, value):
        if value in (NOTSET, ''):
            return None
        return int(value)

    def get_db_prep_save(self, value):
        if not value:
            return ''
        return unicode(value.pk)

    def _get_choices(self):
        return [(obj.pk, obj) for obj in self.queryset]

    def _set_choices(self, value):
        """
        Ignore
        """
    choices = property(_get_choices, _set_choices)

More like this

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

Comments

Please login first before commenting.