Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

# Copyright 2009-2015 Luc Saffre 

# License: BSD (see file COPYING for details) 

 

"""Extends the possibilities for defining choices for fields of a 

Django model. 

 

- Context-sensitive choices 

- Non-limiting choices : 

  specify a pick list of suggestions but leave the possibility 

  to store manually entered values 

- :ref:`learning_combos` 

 

TODO: compare with `django-ajax-selects 

<https://github.com/crucialfelix/django-ajax-selects>`_ 

 

 

.. _learning_combos: 

 

Learning Comboboxes 

------------------- 

 

Choosers inspect the model, and if it defines a method 

`create_FOO_choice`, then the chooser will become "learning": the 

ComboBox will be told to accept also new values, and the server will 

handle these cases accordingly. 

 

""" 

from builtins import str 

from builtins import object 

 

import logging 

logger = logging.getLogger(__name__) 

 

from lino.utils.instantiator import make_converter 

from lino.core import constants 

 

from lino.core.utils import getrqdata 

 

 

class BaseChooser(object): 

    pass 

 

 

class FieldChooser(BaseChooser): 

 

    def __init__(self, field): 

        self.field = field 

 

 

class ChoicesChooser(FieldChooser): 

 

    def __init__(self, field): 

        FieldChooser.__init__(self, field) 

        self.simple_values = type(field.choices[0]) 

 

 

class Chooser(FieldChooser): 

    """A **chooser** holds information about the possible choices of a 

    field. 

 

    """ 

    #~ stored_name = None 

    simple_values = False 

    instance_values = True 

    force_selection = True 

    choice_display_method = None  # not yet used. 

    can_create_choice = False 

 

    def __init__(self, model, field, meth): 

        FieldChooser.__init__(self, field) 

        self.model = model 

        #~ self.field = model._meta.get_field(fldname) 

        self.meth = meth 

        from lino.core.gfks import is_foreignkey 

        if not is_foreignkey(field): 

            self.simple_values = getattr(meth, 'simple_values', False) 

            self.instance_values = getattr(meth, 'instance_values', False) 

            self.force_selection = getattr( 

                meth, 'force_selection', self.force_selection) 

        #~ self.context_params = meth.func_code.co_varnames[1:meth.func_code.co_argcount] 

        self.context_params = meth.context_params 

        #~ self.multiple = meth.multiple 

        #~ self.context_params = meth.func_code.co_varnames[:meth.func_code.co_argcount] 

        #~ print '20100724', meth, self.context_params 

        #~ logger.warning("20100527 %s %s",self.context_params,meth) 

        self.context_values = [] 

        self.context_fields = [] 

        for name in self.context_params: 

            f = self.get_data_elem(name) 

            if f is None: 

                raise Exception( 

                    "No data element '%s' in %s " 

                    "(method %s_choices)" % ( 

                        name, self.model, field.name)) 

            #~ if name == 'p_book': 

                #~ print 20131012, f 

            self.context_fields.append(f) 

            self.context_values.append(name + "Hidden") 

            #~ if isinstance(f,models.ForeignKey): 

                #~ self.context_values.append(name+"Hidden") 

            #~ else: 

                #~ self.context_values.append(name) 

        self.converters = [] 

        #~ try: 

        for f in self.context_fields: 

            cv = make_converter(f) 

            if cv is not None: 

                self.converters.append(cv) 

        #~ except models.FieldDoesNotExist,e: 

            #~ print e 

 

        if hasattr(model, "create_%s_choice" % field.name): 

            self.can_create_choice = True 

 

        m = getattr(model, "%s_choice_display" % field.name, None) 

        if m is not None: 

            self.choice_display_method = m 

 

    def __str__(self): 

        return "Chooser(%s.%s,%s)" % ( 

            self.model.__name__, self.field.name, 

            self.context_params) 

 

    def create_choice(self, obj, text): 

        m = getattr(obj, "create_%s_choice" % self.field.name) 

        return m(text) 

 

    def get_data_elem(self, name): 

        """Calls :meth:`dd.Actor.get_data_elem` or 

        :meth:`dd.Model.get_data_elem` or 

        :meth:`dd.Action.get_data_elem`. 

 

        """ 

        de = self.model.get_data_elem(name) 

        if de is None: 

            return self.model.get_param_elem(name) 

        return de 

 

    def __call__(self, *args, **kw): 

        for i, v in enumerate(args): 

            kw[self.context_fields[i]] = v 

        return self.get_choices(**kw) 

 

    def get_choices(self, **context): 

        """Return a list of choices for this chooser, using keyword parameters 

        as context. 

 

        """ 

        args = [] 

        for varname in self.context_params: 

            args.append(context.get(varname, None)) 

        return self.meth(*args) 

 

    def get_request_choices(self, request, tbl): 

        """ 

        Return a list of choices for this chooser, 

        using a HttpRequest to build the context. 

        """ 

        from django.contrib.contenttypes.models import ContentType 

        kw = {} 

 

        # 20120202 

        if tbl.master_field is not None: 

            rqdata = getrqdata(request) 

            if tbl.master is not None: 

                master = tbl.master 

            else: 

                mt = rqdata.get(constants.URL_PARAM_MASTER_TYPE) 

                try: 

                    master = ContentType.objects.get(pk=mt).model_class() 

                except ContentType.DoesNotExist: 

                    master = None 

 

            pk = rqdata.get(constants.URL_PARAM_MASTER_PK, None) 

            if pk and master: 

                try: 

                    kw[tbl.master_field.name] = master.objects.get(pk=pk) 

                except ValueError: 

                    raise Exception( 

                        "Invalid primary key %r for %s", pk, master.__name__) 

                except master.DoesNotExist: 

                    # todo: ReportRequest should become a subclass of Dialog 

                    # and this exception should call dlg.error() 

                    raise Exception("There's no %s with primary key %r" % 

                                    (master.__name__, pk)) 

 

        for k, v in list(request.GET.items()): 

            kw[str(k)] = v 

 

        # logger.info( 

        #     "20130513 get_request_choices(%r) -> %r", 

        #     tbl, kw) 

 

        for cv in self.converters: 

            kw = cv.convert(**kw) 

 

        if tbl.known_values: 

            kw.update(tbl.known_values) 

 

        if False:  # removed 20120815 #1114 

            #~ ar = tbl.request(ui,request,tbl.default_action) 

            if ar.create_kw: 

                kw.update(ar.create_kw) 

            if ar.known_values: 

                kw.update(ar.known_values) 

            if tbl.master_key: 

                kw[tbl.master_key] = ar.master_instance 

            #~ if tbl.known_values: 

                #~ kw.update(tbl.known_values) 

        return self.get_choices(**kw)  # 20120918b 

 

    def get_text_for_value(self, value, obj): 

        m = getattr(self.field, 'get_text_for_value', None) 

        if m is not None:  # e.g. lino.utils.choicelist.ChoiceListField 

            return m(value) 

        #~ raise NotImplementedError 

        #~ assert not self.simple_values 

        m = getattr(obj, "get_" + self.field.name + "_display") 

        #~ if m is None: 

            #~ raise Exception("") 

        return m(value) 

        #~ raise NotImplementedError("%s : Cannot get text for value %r" % (self.meth,value)) 

 

 

def uses_simple_values(holder, fld): 

    "used by :class:`lino.core.store`" 

    from lino.core.gfks import is_foreignkey 

    if is_foreignkey(fld): 

        return False 

    if holder is not None: 

        ch = holder.get_chooser_for_field(fld.name) 

        if ch is not None: 

            return ch.simple_values 

    choices = list(fld.choices) 

    if len(choices) == 0: 

        return True 

    if type(choices[0]) in (list, tuple): 

        return False 

    return True 

 

 

def _chooser(make, **options): 

    #~ options.setdefault('quick_insert_field',None) 

    def chooser_decorator(fn): 

        def wrapped(*args): 

            #~ print 20101220, args 

            return fn(*args) 

        wrapped.context_params = fn.__code__.co_varnames[ 

            1:fn.__code__.co_argcount] 

        #~ 20120918b wrapped.context_params = fn.func_code.co_varnames[2:fn.func_code.co_argcount] 

        for k, v in list(options.items()): 

            setattr(wrapped, k, v) 

        return make(wrapped) 

        # return classmethod(wrapped) 

        # A chooser on an action must not turn it into a classmethod 

    return chooser_decorator 

 

 

def chooser(**options): 

    "Decorator which turns the method into a chooser." 

    return _chooser(classmethod, **options) 

 

 

def noop(x): 

    return x 

 

 

def action_chooser(**options): 

    return _chooser(noop, **options)