from django conf import settings from django db import models from dja

 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
from django.conf import settings
from django.db import models
from django import forms
import datetime
from libs.modelfields import PickleField, JSONField
if getattr(settings, 'USE_CPICKLE', False):
import cPickle as pickle
else:
import pickle
class EAVWidget(forms.widgets.MultiWidget):
"""
"""
def __init__(self, add_fields=None, attrs={}):
self.add_fields = add_fields or []
attrs['style'] = 'width: auto;'
widgets = [forms.widgets.TextInput(attrs=attrs) for i in xrange(len(self.add_fields))]
super(EAVWidget, self).__init__(widgets, attrs)
def format_output(self, rendered_widgets):
if self.add_fields:
out = ['<table><tr>']
for i, w in enumerate(rendered_widgets):
out += ['<td style="padding:0 4px 0 0; border:0;">',
'<label style="white-space: nowrap;">',
self.add_fields[i].name,
':&nbsp;',
w,
'</label></td>']
out += ['</tr></table>']
else:
out = rendered_widgets
return u''.join(out)
def decompress(self, value):
try:
# value = pickle.loads(value.encode('utf8'))
out = []
for f in self.add_fields:
out.append(value.get(f.slug, ''))
return out
except:
return [None]*len(self.add_fields)
class EAVField(forms.fields.MultiValueField):
widget=EAVWidget
def __init__(self, add_fields=None, *args, **kwargs):
self.add_fields = add_fields or []
if self.add_fields:
fields = [forms.fields.CharField(required=False) for i in xrange(len(add_fields))]
self.widget = self.widget(add_fields)
else:
fields = []
super(EAVField, self).__init__(fields, *args, **kwargs)
def compress(self, data_list):
out = {}
for i,f in enumerate(self.add_fields):
try:
out[f.slug] = data_list[i]
except IndexError:
pass
# out = pickle.dumps(out)
return out
class EAV_PickleField(PickleField):
editable = True
class EAV_JSONField(JSONField):
def formfield(self, **kwargs):
kwargs['form_class'] = EAVField
kwargs['widget'] = EAVWidget
return super(EAV_JSONField, self).formfield(**kwargs)