##// END OF EJS Templates
Avoid add mix line type to RC configurations...
Juan C. Espinoza -
r142:e1a704308026
parent child
Show More
@@ -1,378 +1,381
1 1 import os
2 2 import ast
3 3 import json
4 4
5 5 from django import forms
6 6 from django.utils.safestring import mark_safe
7 7 from apps.main.models import Device
8 8 from apps.main.forms import add_empty_choice
9 9 from .models import RCConfiguration, RCLine, RCLineType, RCLineCode
10 10 from .widgets import KmUnitWidget, KmUnitHzWidget, KmUnitDcWidget, UnitKmWidget, DefaultWidget, CodesWidget, HiddenWidget, HCheckboxSelectMultiple
11 11
12 12 def create_choices_from_model(model, conf_id, all=False):
13 13
14 14 if model=='RCLine':
15 15 instance = RCConfiguration.objects.get(pk=conf_id)
16 16 choices = [(line.pk, line.get_name()) for line in instance.get_lines(line_type__name='tx')]
17 17 choices = add_empty_choice(choices, label='All')
18 18 else:
19 19 instance = globals()[model]
20 20 choices = instance.objects.all().values_list('pk', 'name')
21 21
22 22 return choices
23 23
24 24
25 25 class ExtFileField(forms.FileField):
26 26 """
27 27 Same as forms.FileField, but you can specify a file extension whitelist.
28 28
29 29 >>> from django.core.files.uploadedfile import SimpleUploadedFile
30 30 >>>
31 31 >>> t = ExtFileField(ext_whitelist=(".pdf", ".txt"))
32 32 >>>
33 33 >>> t.clean(SimpleUploadedFile('filename.pdf', 'Some File Content'))
34 34 >>> t.clean(SimpleUploadedFile('filename.txt', 'Some File Content'))
35 35 >>>
36 36 >>> t.clean(SimpleUploadedFile('filename.exe', 'Some File Content'))
37 37 Traceback (most recent call last):
38 38 ...
39 39 ValidationError: [u'Not allowed filetype!']
40 40 """
41 41 def __init__(self, *args, **kwargs):
42 42 extensions = kwargs.pop("extensions")
43 43 self.extensions = [i.lower() for i in extensions]
44 44
45 45 super(ExtFileField, self).__init__(*args, **kwargs)
46 46
47 47 def clean(self, *args, **kwargs):
48 48 data = super(ExtFileField, self).clean(*args, **kwargs)
49 49 filename = data.name
50 50 ext = os.path.splitext(filename)[1]
51 51 ext = ext.lower()
52 52 if ext not in self.extensions:
53 53 raise forms.ValidationError('Not allowed file type: %s' % ext)
54 54
55 55
56 56 class RCConfigurationForm(forms.ModelForm):
57 57
58 58 def __init__(self, *args, **kwargs):
59 59 super(RCConfigurationForm, self).__init__(*args, **kwargs)
60 60
61 61 instance = getattr(self, 'instance', None)
62 62
63 63 if instance and instance.pk:
64 64
65 65 devices = Device.objects.filter(device_type__name='rc')
66 66 if instance.experiment:
67 67 self.fields['experiment'].widget.attrs['read_only'] = True
68 68 #self.fields['experiment'].widget.choices = [(instance.experiment.id, instance.experiment)]
69 69 self.fields['device'].widget.choices = [(device.id, device) for device in devices]
70 70 self.fields['ipp'].widget = KmUnitHzWidget(attrs={'km2unit':instance.km2unit})
71 71 self.fields['clock'].widget.attrs['readonly'] = True
72 72
73 73 self.fields['time_before'].label = mark_safe(self.fields['time_before'].label)
74 74 self.fields['time_after'].label = mark_safe(self.fields['time_after'].label)
75 75
76 76 if 'initial' in kwargs and 'experiment' in kwargs['initial'] and kwargs['initial']['experiment'] not in (0, '0'):
77 77 self.fields['experiment'].widget.attrs['readonly'] = True
78 78
79 79 class Meta:
80 80 model = RCConfiguration
81 81 exclude = ('type', 'parameters', 'status', 'total_units', 'mix')
82 82
83 83 def clean(self):
84 84 form_data = super(RCConfigurationForm, self).clean()
85 85
86 86 if 'clock_divider' in form_data:
87 87 if form_data['clock_divider']<1:
88 88 self.add_error('clock_divider', 'Invalid Value')
89 89 else:
90 90 if form_data['ipp']*(20./3*(form_data['clock_in']/form_data['clock_divider']))%10<>0:
91 91 self.add_error('ipp', 'Invalid IPP units={}'.format(form_data['ipp']*(20./3*(form_data['clock_in']/form_data['clock_divider']))))
92 92
93 93 return form_data
94 94
95 95 def save(self):
96 96 conf = super(RCConfigurationForm, self).save()
97 97 conf.total_units = conf.ipp*conf.ntx*conf.km2unit
98 98 conf.save()
99 99 return conf
100 100
101 101
102 102 class RCMixConfigurationForm(forms.Form):
103 103
104 104 clock_in = forms.CharField(widget=forms.HiddenInput())
105 105 clock_divider = forms.CharField(widget=forms.HiddenInput())
106 106 name = forms.CharField()
107 107 experiment = forms.ChoiceField()
108 108 mode = forms.ChoiceField(widget=forms.RadioSelect(),
109 109 choices=[(0, 'Parallel'), (1, 'Sequence')],
110 110 initial=0)
111 111 operation = forms.ChoiceField(widget=forms.RadioSelect(),
112 112 choices=[(0, 'OR'), (1, 'XOR'), (2, 'AND'), (3, 'NAND')],
113 113 initial=1)
114 114 delay = forms.CharField()
115 115 mask = forms.MultipleChoiceField(choices=[(0, 'L1'),(1, 'L2'),(2, 'L3'),(3, 'L4'),(4, 'L5'),(5, 'L6'),(6, 'L7'),(7, 'L8')],
116 116 widget=HCheckboxSelectMultiple())
117 117 result = forms.CharField(required=False,
118 118 widget=forms.Textarea(attrs={'readonly':True, 'rows':5, 'class':'tabuled'}))
119 119
120 120 def __init__(self, *args, **kwargs):
121 121 confs = kwargs.pop('confs', [])
122 122 if confs:
123 123 km2unit = confs[0].km2unit
124 124 clock_in = confs[0].clock_in
125 125 clock_divider = confs[0].clock_divider
126 126 else:
127 127 km2unit = clock_in = clock_divider = 0
128 128 super(RCMixConfigurationForm, self).__init__(*args, **kwargs)
129 129 self.fields['experiment'].choices = [(conf.pk, '{} | {}'.format(conf.pk, conf.name)) for conf in confs]
130 130 self.fields['delay'].widget = KmUnitWidget(attrs = {'km2unit':km2unit})
131 131 self.fields['clock_in'].initial = clock_in
132 132 self.fields['clock_divider'].initial = clock_divider
133 133
134 134
135 135 class RCLineForm(forms.ModelForm):
136 136
137 137 def __init__(self, *args, **kwargs):
138 138 self.extra_fields = kwargs.pop('extra_fields', [])
139 139 super(RCLineForm, self).__init__(*args, **kwargs)
140 140
141 141 if 'initial' in kwargs and 'line_type' in kwargs['initial']:
142 142 line_type = RCLineType.objects.get(pk=kwargs['initial']['line_type'])
143 143
144 144 if 'code_id' in kwargs['initial']:
145 145 model_initial = kwargs['initial']['code_id']
146 146 else:
147 147 model_initial = 0
148 148
149 149 params = json.loads(line_type.params)
150 150
151 151 for label, value in self.extra_fields.items():
152 152 if label=='params':
153 153 continue
154 154
155 155 if 'model' in params[label]:
156 156 self.fields[label] = forms.ChoiceField(choices=create_choices_from_model(params[label]['model'],
157 157 kwargs['initial']['rc_configuration']),
158 158 initial=model_initial)
159 159
160 160
161 161 else:
162 162 if label=='codes' and 'code_id' in kwargs['initial']:
163 163 self.fields[label] = forms.CharField(initial=RCLineCode.objects.get(pk=kwargs['initial']['code_id']).codes)
164 164 else:
165 165 self.fields[label] = forms.CharField(initial=value['value'])
166 166
167 167 if label=='codes':
168 168 self.fields[label].widget = CodesWidget()
169 169
170 170 if self.data:
171 171 line_type = RCLineType.objects.get(pk=self.data['line_type'])
172 172
173 173 if 'code_id' in self.data:
174 174 model_initial = self.data['code_id']
175 175 else:
176 176 model_initial = 0
177 177
178 178 params = json.loads(line_type.params)
179 179
180 180 for label, value in self.extra_fields.items():
181 181 if label=='params':
182 182 continue
183 183
184 184 if 'model' in params[label]:
185 185 self.fields[label] = forms.ChoiceField(choices=create_choices_from_model(params[label]['model'],
186 186 self.data['rc_configuration']),
187 187 initial=model_initial)
188 188
189 189
190 190 else:
191 191 if label=='codes' and 'code' in self.data:
192 192 self.fields[label] = forms.CharField(initial=self.data['codes'])
193 193 else:
194 194 self.fields[label] = forms.CharField(initial=self.data[label])
195 195
196 196 if label=='codes':
197 197 self.fields[label].widget = CodesWidget()
198 198
199 199
200 200 class Meta:
201 201 model = RCLine
202 202 fields = ('rc_configuration', 'line_type', 'channel')
203 203 widgets = {
204 204 'channel': forms.HiddenInput(),
205 205 }
206 206
207 207
208 208 def clean(self):
209 209
210 210 form_data = self.cleaned_data
211 211 if 'code' in self.data and self.data['TX_ref']=="0":
212 212 self.add_error('TX_ref', 'Choose a valid TX reference')
213 213
214 if RCLineType.objects.get(pk=self.data['line_type']).name=='mix':
215 self.add_error('line_type', 'Invalid Line type')
216
214 217 return form_data
215 218
216 219
217 220 def save(self):
218 221 line = super(RCLineForm, self).save()
219 222
220 223 #auto add channel
221 224 line.channel = RCLine.objects.filter(rc_configuration=line.rc_configuration).count()-1
222 225
223 226 #auto add position for TX, TR & CODE
224 227 if line.line_type.name in ('tx', ):
225 228 line.position = RCLine.objects.filter(rc_configuration=line.rc_configuration, line_type=line.line_type).count()-1
226 229
227 230 #save extra fields in params
228 231 params = {}
229 232 for label, value in self.extra_fields.items():
230 233 if label=='params':
231 234 params['params'] = []
232 235 elif label=='codes':
233 236 params[label] = [s for s in self.data[label].split('\r\n') if s]
234 237 else:
235 238 params[label] = self.data[label]
236 239 line.params = json.dumps(params)
237 240 line.save()
238 241 return
239 242
240 243
241 244 class RCLineViewForm(forms.Form):
242 245
243 246 def __init__(self, *args, **kwargs):
244 247
245 248 extra_fields = kwargs.pop('extra_fields')
246 249 line = kwargs.pop('line')
247 250 subform = kwargs.pop('subform', False)
248 251 super(RCLineViewForm, self).__init__(*args, **kwargs)
249 252
250 253 if subform:
251 254 params = json.loads(line.line_type.params)['params']
252 255 else:
253 256 params = json.loads(line.line_type.params)
254 257
255 258 for label, value in extra_fields.items():
256 259
257 260 if label=='params':
258 261 continue
259 262 if 'ref' in label:
260 263 if value in (0, '0'):
261 264 value = 'All'
262 265 else:
263 266 value = RCLine.objects.get(pk=value).get_name()
264 267 elif label=='code':
265 268 value = RCLineCode.objects.get(pk=value).name
266 269
267 270 self.fields[label] = forms.CharField(initial=value)
268 271
269 272 if 'widget' in params[label]:
270 273 km2unit = line.rc_configuration.km2unit
271 274 if params[label]['widget']=='km':
272 275 self.fields[label].widget = KmUnitWidget(attrs={'line':line, 'km2unit':km2unit, 'disabled':True})
273 276 elif params[label]['widget']=='unit':
274 277 self.fields[label].widget = UnitKmWidget(attrs={'line':line, 'km2unit':km2unit, 'disabled':True})
275 278 elif params[label]['widget']=='dc':
276 279 self.fields[label].widget = KmUnitDcWidget(attrs={'line':line, 'km2unit':km2unit, 'disabled':True})
277 280 elif params[label]['widget']=='codes':
278 281 self.fields[label].widget = CodesWidget(attrs={'line':line, 'km2unit':km2unit, 'disabled':True})
279 282 else:
280 283 self.fields[label].widget = DefaultWidget(attrs={'disabled':True})
281 284
282 285
283 286 class RCLineEditForm(forms.ModelForm):
284 287
285 288 def __init__(self, *args, **kwargs):
286 289
287 290 extra_fields = kwargs.pop('extra_fields', [])
288 291 conf = kwargs.pop('conf', False)
289 292 line = kwargs.pop('line')
290 293 subform = kwargs.pop('subform', False)
291 294
292 295 super(RCLineEditForm, self).__init__(*args, **kwargs)
293 296
294 297 if subform is not False:
295 298 params = json.loads(line.line_type.params)['params']
296 299 count = subform
297 300 else:
298 301 params = json.loads(line.line_type.params)
299 302 count = -1
300 303
301 304 for label, value in extra_fields.items():
302 305
303 306 if label in ('params',):
304 307 continue
305 308 if 'help' in params[label]:
306 309 help_text = params[label]['help']
307 310 else:
308 311 help_text = ''
309 312
310 313 if 'model' in params[label]:
311 314 self.fields[label] = forms.ChoiceField(choices=create_choices_from_model(params[label]['model'], conf.id),
312 315 initial=value,
313 316 widget=forms.Select(attrs={'name':'%s|%s|%s' % (count, line.id, label)}),
314 317 help_text=help_text)
315 318
316 319 else:
317 320
318 321 self.fields[label] = forms.CharField(initial=value, help_text=help_text)
319 322
320 323 if label in ('code', ):
321 324 self.fields[label].widget = HiddenWidget(attrs={'name':'%s|%s|%s' % (count, line.id, label)})
322 325
323 326 elif 'widget' in params[label]:
324 327 km2unit = line.rc_configuration.km2unit
325 328 if params[label]['widget']=='km':
326 329 self.fields[label].widget = KmUnitWidget(attrs={'line':line, 'km2unit':km2unit, 'name':'%s|%s|%s' % (count, line.id, label)})
327 330 elif params[label]['widget']=='unit':
328 331 self.fields[label].widget = UnitKmWidget(attrs={'line':line, 'km2unit':km2unit, 'name':'%s|%s|%s' % (count, line.id, label)})
329 332 elif params[label]['widget']=='dc':
330 333 self.fields[label].widget = KmUnitDcWidget(attrs={'line':line, 'km2unit':km2unit, 'name':'%s|%s|%s' % (count, line.id, label)})
331 334 elif params[label]['widget']=='codes':
332 335 self.fields[label].widget = CodesWidget(attrs={'line':line, 'km2unit':km2unit, 'name':'%s|%s|%s' % (count, line.id, label)})
333 336 else:
334 337 self.fields[label].widget = DefaultWidget(attrs={'name':'%s|%s|%s' % (count, line.id, label)})
335 338
336 339
337 340 class Meta:
338 341 model = RCLine
339 342 exclude = ('rc_configuration', 'line_type', 'channel', 'position', 'params', 'pulses')
340 343
341 344
342 345 class RCSubLineEditForm(forms.Form):
343 346
344 347 def __init__(self, *args, **kwargs):
345 348 extra_fields = kwargs.pop('extra_fields')
346 349 count = kwargs.pop('count')
347 350 line = kwargs.pop('line')
348 351 super(RCSubLineEditForm, self).__init__(*args, **kwargs)
349 352 for label, value in extra_fields.items():
350 353 self.fields[label] = forms.CharField(initial=value,
351 354 widget=forms.TextInput(attrs={'name':'%s|%s|%s' % (count, line, label)}))
352 355
353 356
354 357 class RCImportForm(forms.Form):
355 358
356 359 file_name = ExtFileField(extensions=['.racp', '.json', '.dat'])
357 360
358 361
359 362 class RCLineCodesForm(forms.ModelForm):
360 363
361 364 def __init__(self, *args, **kwargs):
362 365 super(RCLineCodesForm, self).__init__(*args, **kwargs)
363 366
364 367 if 'initial' in kwargs:
365 368 self.fields['code'] = forms.ChoiceField(choices=RCLineCode.objects.all().values_list('pk', 'name'),
366 369 initial=kwargs['initial']['code'])
367 370 if 'instance' in kwargs:
368 371 self.fields['code'] = forms.ChoiceField(choices=RCLineCode.objects.all().values_list('pk', 'name'),
369 372 initial=kwargs['instance'].pk)
370 373
371 374 self.fields['codes'].widget = CodesWidget()
372 375
373 376
374 377 class Meta:
375 378 model = RCLineCode
376 379 exclude = ('name',)
377 380
378 381 No newline at end of file
@@ -1,372 +1,373
1 1
2 2 import json
3 3
4 4 from django.contrib import messages
5 5 from django.utils.safestring import mark_safe
6 6 from django.shortcuts import render, redirect, get_object_or_404, HttpResponse
7 7
8 8 from apps.main.models import Configuration, Experiment, Device
9 9 from apps.main.views import sidebar
10 10
11 11 from .models import RCConfiguration, RCLine, RCLineType, RCLineCode
12 12 from .forms import RCConfigurationForm, RCLineForm, RCLineViewForm, RCLineEditForm, RCImportForm, RCLineCodesForm
13 13
14 14
15 15 def conf(request, conf_id):
16 16
17 17 conf = get_object_or_404(RCConfiguration, pk=conf_id)
18 18
19 19 lines = RCLine.objects.filter(rc_configuration=conf).order_by('channel')
20 20
21 21 for line in lines:
22 22 params = json.loads(line.params)
23 23 line.form = RCLineViewForm(extra_fields=params, line=line)
24 24 if 'params' in params:
25 25 line.subforms = [RCLineViewForm(extra_fields=fields, line=line, subform=True) for fields in params['params']]
26 26
27 27 kwargs = {}
28 28 kwargs['dev_conf'] = conf
29 29 kwargs['rc_lines'] = lines
30 30 kwargs['dev_conf_keys'] = ['name', 'ipp_unit', 'ntx', 'clock_in', 'clock_divider', 'clock',
31 31 'time_before', 'time_after', 'sync', 'sampling_reference', 'control_tx', 'control_sw']
32 32
33 33 kwargs['title'] = 'RC Configuration'
34 34 kwargs['suptitle'] = 'Details'
35 35
36 36 kwargs['button'] = 'Edit Configuration'
37 37 ###### SIDEBAR ######
38 38 kwargs.update(sidebar(conf=conf))
39 39
40 40 return render(request, 'rc_conf.html', kwargs)
41 41
42 42
43 43 def conf_edit(request, conf_id):
44 44
45 45 conf = get_object_or_404(RCConfiguration, pk=conf_id)
46 46
47 47 lines = RCLine.objects.filter(rc_configuration=conf).order_by('channel')
48 48
49 49 for line in lines:
50 50 params = json.loads(line.params)
51 51 line.form = RCLineEditForm(conf=conf, line=line, extra_fields=params)
52 52 line.subform = False
53 53
54 54 if 'params' in params:
55 55 line.subforms = [RCLineEditForm(extra_fields=fields, line=line, subform=i) for i, fields in enumerate(params['params'])]
56 56 line.subform = True
57 57
58 58 if request.method=='GET':
59 59
60 60 form = RCConfigurationForm(instance=conf)
61 61
62 62 elif request.method=='POST':
63 63
64 64 line_data = {}
65 65 conf_data = {}
66 66 extras = []
67 67
68 68 #classified post fields
69 69 for label,value in request.POST.items():
70 70 if label=='csrfmiddlewaretoken':
71 71 continue
72 72
73 73 if label.count('|')==0:
74 74 conf_data[label] = value
75 75 continue
76 76
77 77 elif label.split('|')[0]<>'-1':
78 78 extras.append(label)
79 79 continue
80 80
81 81 x, pk, name = label.split('|')
82 82
83 83 if name=='codes':
84 84 value = [s for s in value.split('\r\n') if s]
85 85
86 86 if pk in line_data:
87 87 line_data[pk][name] = value
88 88 else:
89 89 line_data[pk] = {name:value}
90 90
91 91 #update conf
92 92 form = RCConfigurationForm(conf_data, instance=conf)
93 93
94 94 if form.is_valid():
95 95
96 96 form.save()
97 97
98 98 #update lines fields
99 99 extras.sort()
100 100 for label in extras:
101 101 x, pk, name = label.split('|')
102 102 if pk not in line_data:
103 103 line_data[pk] = {}
104 104 if 'params' not in line_data[pk]:
105 105 line_data[pk]['params'] = []
106 106 if len(line_data[pk]['params'])<int(x)+1:
107 107 line_data[pk]['params'].append({})
108 108 line_data[pk]['params'][int(x)][name] = float(request.POST[label])
109 109
110 110 for pk, params in line_data.items():
111 111 line = RCLine.objects.get(pk=pk)
112 112 if line.line_type.name in ('windows', 'prog_pulses'):
113 113 if 'params' not in params:
114 114 params['params'] = []
115 115 line.params = json.dumps(params)
116 116 line.save()
117 117
118 118 #update pulses field
119 119 conf.update_pulses()
120 120
121 121 messages.success(request, 'RC Configuration successfully updated')
122 122
123 123 return redirect(conf.get_absolute_url())
124 124
125 125 kwargs = {}
126 126 kwargs['dev_conf'] = conf
127 127 kwargs['form'] = form
128 128 kwargs['rc_lines'] = lines
129 129 kwargs['edit'] = True
130 130
131 131 kwargs['title'] = 'RC Configuration'
132 132 kwargs['suptitle'] = 'Edit'
133 133 kwargs['button'] = 'Update'
134 134 kwargs['previous'] = conf.get_absolute_url()
135 135
136 136 return render(request, 'rc_conf_edit.html', kwargs)
137 137
138 138
139 139 def add_line(request, conf_id, line_type_id=None, code_id=None):
140 140
141 141 conf = get_object_or_404(RCConfiguration, pk=conf_id)
142 142
143 143 if request.method=='GET':
144 144 if line_type_id:
145 145 line_type = get_object_or_404(RCLineType, pk=line_type_id)
146 146
147 147 if code_id:
148 148 form = RCLineForm(initial={'rc_configuration':conf_id, 'line_type': line_type_id, 'code_id': code_id},
149 149 extra_fields=json.loads(line_type.params))
150 150 else:
151 151 form = RCLineForm(initial={'rc_configuration':conf_id, 'line_type': line_type_id},
152 152 extra_fields=json.loads(line_type.params))
153 153 else:
154 154 line_type = {'id':0}
155 155 form = RCLineForm(initial={'rc_configuration':conf_id})
156 156
157 157 if request.method=='POST':
158 158
159 159 line_type = get_object_or_404(RCLineType, pk=line_type_id)
160 160 form = RCLineForm(request.POST,
161 161 extra_fields=json.loads(line_type.params))
162 162
163 163 if form.is_valid():
164 164 form.save()
165 165 form.instance.update_pulses()
166 166 return redirect('url_edit_rc_conf', conf.id)
167 167
168 168 kwargs = {}
169 169 kwargs['form'] = form
170 170 kwargs['title'] = 'RC Configuration'
171 171 kwargs['suptitle'] = 'Add Line'
172 172 kwargs['button'] = 'Add'
173 173 kwargs['previous'] = conf.get_absolute_url_edit()
174 174 kwargs['dev_conf'] = conf
175 175 kwargs['line_type'] = line_type
176 176
177 177 return render(request, 'rc_add_line.html', kwargs)
178 178
179 179 def edit_codes(request, conf_id, line_id, code_id=None):
180 180
181 181 conf = get_object_or_404(RCConfiguration, pk=conf_id)
182 182 line = get_object_or_404(RCLine, pk=line_id)
183 183 params = json.loads(line.params)
184 184
185 185 if request.method=='GET':
186 186 if code_id:
187 187 code = get_object_or_404(RCLineCode, pk=code_id)
188 188 form = RCLineCodesForm(instance=code)
189 189 else:
190 190 initial = {'code': params['code'],
191 191 'codes': params['codes'] if 'codes' in params else [],
192 192 'number_of_codes': len(params['codes']) if 'codes' in params else 0,
193 193 'bits_per_code': len(params['codes'][0]) if 'codes' in params else 0,
194 194 }
195 195 form = RCLineCodesForm(initial=initial)
196 196
197 197 if request.method=='POST':
198 198 form = RCLineCodesForm(request.POST)
199 199 if form.is_valid():
200 200 params['code'] = request.POST['code']
201 201 params['codes'] = [s for s in request.POST['codes'].split('\r\n') if s]
202 202 line.params = json.dumps(params)
203 203 line.save()
204 204 messages.success(request, 'Line: "%s" has been updated.' % line)
205 205 return redirect('url_edit_rc_conf', conf.id)
206 206
207 207 kwargs = {}
208 208 kwargs['form'] = form
209 209 kwargs['title'] = line
210 210 kwargs['suptitle'] = 'Edit'
211 211 kwargs['button'] = 'Update'
212 212 kwargs['dev_conf'] = conf
213 213 kwargs['previous'] = conf.get_absolute_url_edit()
214 214 kwargs['line'] = line
215 215
216 216 return render(request, 'rc_edit_codes.html', kwargs)
217 217
218 218 def add_subline(request, conf_id, line_id):
219 219
220 220 conf = get_object_or_404(RCConfiguration, pk=conf_id)
221 221 line = get_object_or_404(RCLine, pk=line_id)
222 222
223 223 if request.method == 'POST':
224 224 if line:
225 225 params = json.loads(line.params)
226 226 subparams = json.loads(line.line_type.params)
227 227 if 'params' in subparams:
228 228 dum = {}
229 229 for key, value in subparams['params'].items():
230 230 dum[key] = value['value']
231 231 params['params'].append(dum)
232 232 line.params = json.dumps(params)
233 233 line.save()
234 234 return redirect('url_edit_rc_conf', conf.id)
235 235
236 236 kwargs = {}
237 237
238 238 kwargs['title'] = 'Add new'
239 239 kwargs['suptitle'] = '%s to %s' % (line.line_type.name, line)
240 240
241 241 return render(request, 'confirm.html', kwargs)
242 242
243 243 def remove_line(request, conf_id, line_id):
244 244
245 245 conf = get_object_or_404(RCConfiguration, pk=conf_id)
246 246 line = get_object_or_404(RCLine, pk=line_id)
247 247
248 248 if request.method == 'POST':
249 249 if line:
250 250 try:
251 251 channel = line.channel
252 252 line.delete()
253 253 for ch in range(channel+1, RCLine.objects.filter(rc_configuration=conf).count()+1):
254 254 l = RCLine.objects.get(rc_configuration=conf, channel=ch)
255 255 l.channel = l.channel-1
256 256 l.save()
257 257 messages.success(request, 'Line: "%s" has been deleted.' % line)
258 258 except:
259 259 messages.error(request, 'Unable to delete line: "%s".' % line)
260 260
261 261 return redirect('url_edit_rc_conf', conf.id)
262 262
263 263 kwargs = {}
264 264
265 265 kwargs['object'] = line
266 kwargs['delete_view'] = True
267 kwargs['title'] = 'Confirm delete'
266 kwargs['delete'] = True
267 kwargs['title'] = 'Delete'
268 kwargs['suptitle'] = 'Line'
268 269 kwargs['previous'] = conf.get_absolute_url_edit()
269 270 return render(request, 'confirm.html', kwargs)
270 271
271 272
272 273 def remove_subline(request, conf_id, line_id, subline_id):
273 274
274 275 conf = get_object_or_404(RCConfiguration, pk=conf_id)
275 276 line = get_object_or_404(RCLine, pk=line_id)
276 277
277 278 if request.method == 'POST':
278 279 if line:
279 280 params = json.loads(line.params)
280 281 params['params'].remove(params['params'][int(subline_id)-1])
281 282 line.params = json.dumps(params)
282 283 line.save()
283 284
284 285 return redirect('url_edit_rc_conf', conf.id)
285 286
286 287 kwargs = {}
287 288
288 289 kwargs['object'] = line
289 290 kwargs['object_name'] = line.line_type.name
290 291 kwargs['delete_view'] = True
291 292 kwargs['title'] = 'Confirm delete'
292 293
293 294 return render(request, 'confirm.html', kwargs)
294 295
295 296
296 297 def update_lines_position(request, conf_id):
297 298
298 299 conf = get_object_or_404(RCConfiguration, pk=conf_id)
299 300
300 301 if request.method=='POST':
301 302 ch = 0
302 303 for item in request.POST['items'].split('&'):
303 304 line = RCLine.objects.get(pk=item.split('=')[-1])
304 305 line.channel = ch
305 306 line.save()
306 307 ch += 1
307 308
308 309 lines = RCLine.objects.filter(rc_configuration=conf).order_by('channel')
309 310
310 311 for line in lines:
311 312 params = json.loads(line.params)
312 313 line.form = RCLineEditForm(conf=conf, line=line, extra_fields=params)
313 314
314 315 if 'params' in params:
315 316 line.subform = True
316 317 line.subforms = [RCLineEditForm(extra_fields=fields, line=line, subform=i) for i, fields in enumerate(params['params'])]
317 318
318 319 html = render(request, 'rc_lines.html', {'dev_conf':conf, 'rc_lines':lines, 'edit':True})
319 320 data = {'html': html.content}
320 321
321 322 return HttpResponse(json.dumps(data), content_type="application/json")
322 323 return redirect('url_edit_rc_conf', conf.id)
323 324
324 325
325 326 def import_file(request, conf_id):
326 327
327 328 conf = get_object_or_404(RCConfiguration, pk=conf_id)
328 329 if request.method=='POST':
329 330 form = RCImportForm(request.POST, request.FILES)
330 331 if form.is_valid():
331 332 try:
332 333 conf.update_from_file(request.FILES['file_name'])
333 334 messages.success(request, 'Configuration "%s" loaded succesfully' % request.FILES['file_name'])
334 335 return redirect(conf.get_absolute_url_edit())
335 336
336 337 except Exception as e:
337 338 messages.error(request, 'Error parsing file: "%s" - %s' % (request.FILES['file_name'], e))
338 339
339 340 else:
340 341 messages.warning(request, 'Your current configuration will be replaced')
341 342 form = RCImportForm()
342 343
343 344 kwargs = {}
344 345 kwargs['form'] = form
345 346 kwargs['title'] = 'RC Configuration'
346 347 kwargs['suptitle'] = 'Import file'
347 348 kwargs['button'] = 'Upload'
348 349 kwargs['previous'] = conf.get_absolute_url()
349 350
350 351 return render(request, 'rc_import.html', kwargs)
351 352
352 353
353 354 def plot_pulses(request, conf_id):
354 355
355 356 conf = get_object_or_404(RCConfiguration, pk=conf_id)
356 357
357 358 script, div = conf.plot_pulses()
358 359
359 360 kwargs = {}
360 361
361 362 kwargs['title'] = 'RC Pulses'
362 363 kwargs['suptitle'] = conf.name
363 364 kwargs['div'] = mark_safe(div)
364 365 kwargs['script'] = mark_safe(script)
365 366 kwargs['units'] = conf.km2unit
366 367 kwargs['kms'] = 1/conf.km2unit
367 368
368 369 if 'json' in request.GET:
369 370 return HttpResponse(json.dumps({'div':mark_safe(div), 'script':mark_safe(script)}), content_type="application/json")
370 371 else:
371 372 return render(request, 'rc_pulses.html', kwargs)
372 373
General Comments 0
You need to be logged in to leave comments. Login now