ajax_lexeme_view.py
26.5 KB
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
# -*- coding: utf-8 -*-
import datetime
from django.contrib.auth.models import User
from django.core.cache import cache
from django.db.models import Max
from dictionary.ajax_lexeme_slickgrid import LexemeQuery
from dictionary.auto_derivatives import lexeme_derivatives, create_derivative
from dictionary.models import Lexeme, LexemeInflectionPattern, PartOfSpeech, \
Pattern, Vocabulary, Qualifier, prepare_table, ClassificationValue, \
CrossReference, InputLexeme, CrossReferenceType, editable_vocabularies, \
visible_qualifiers, LexemeAttributeValue, Gender, LexemeAttribute, \
LexemeAV, LexemeCV, Classification
from dictionary.forms import LexemeEditForm, LIPEditForm, ClassificationForm, \
CrossReferenceForm, ActionFieldForm, ACTION_FIELDS,\
LexemeOpenAttributeForm, LexemeClosedAttributeForm, \
LexemeMultipleAttributeForm
from common.decorators import ajax, AjaxError, render_ajax
from common.util import error_messages, bisect_left, format_date
from dictionary.util import refresh_lexeme_data
@render_ajax(
template='inflection_tables.html', method='get', login_required=False)
def inflection_tables(request, variant, lexeme_id):
lexeme = Lexeme.all_objects.get(pk=lexeme_id) # może być nowy
if not lexeme.perm(request.user, 'view'):
raise AjaxError('access denied')
qualifiers = visible_qualifiers(request.user)
tables = lexeme.inflection_tables(variant, qualifiers=qualifiers)
try:
pos_name = lexeme.attribute_value(
LexemeAttribute.objects.get(name=u'dokładniej')).value
except AttributeError:
pos_name = lexeme.part_of_speech.full_name
return {
'tables': tables,
'lexeme': lexeme,
'part_of_speech': pos_name,
'cross_references': lexeme.cross_references(request.user),
'info': lexeme.sgjp_info(),
}
@render_ajax(template='table_preview.html', method='get')
def table_preview(request, lexeme_id, lip_id, pattern, attr_data=None,
gender=None, entry=None):
lexeme = Lexeme.all_objects.get(pk=lexeme_id)
if not lexeme.perm(request.user, 'view'):
raise AjaxError('access denied')
try:
if entry is not None:
lexeme.entry = entry
pattern = Pattern.objects.get(name=pattern)
gender = Gender.objects.get(id=gender) if gender else None
if attr_data:
attr_vals = LexemeAttributeValue.objects.filter(
id__in=attr_data)
else:
attr_vals = None
if lip_id.startswith('lip_add'):
lip = LexemeInflectionPattern(lexeme=lexeme, index=0)
else:
lip = LexemeInflectionPattern.objects.get(pk=int(lip_id[3:]))
lip.pattern = pattern
lip.gender = gender
lip.root = lip.get_root()
qualifiers = visible_qualifiers(request.user)
table = lip.inflection_table(
'0', separated=True, qualifiers=qualifiers, edit_view=True,
attr_vals=attr_vals)
prepare_table(table)
except Pattern.DoesNotExist:
table = None
return {'table': table, 'color_scheme': lexeme.part_of_speech.color_scheme}
@ajax(template='odm_forms.html', method='get')
def odm_forms(request, lexeme_id):
to_return = {}
l = Lexeme.all_objects.get(pk=lexeme_id)
if not l.perm(request.user, 'view'):
raise AjaxError('access denied')
odm_lexemes = []
for l in InputLexeme.objects.filter(entry=l.entry):
odm_lexemes.append(list(l.inputform_set.values_list('form', flat=True)))
to_return['odm_lexemes'] = odm_lexemes
return to_return
def attribute_forms(l, part_of_speech=None, genders=None):
for attr, v in l.attributes_values(part_of_speech, genders):
if not attr.closed:
form_class = LexemeOpenAttributeForm
elif not attr.multiple:
form_class = LexemeClosedAttributeForm
else:
form_class = LexemeMultipleAttributeForm
if attr.multiple:
prefix = 'attrmulti%s' % attr.pk
else:
prefix = 'attr%s' % attr.pk
yield form_class(attribute=attr, initial_value=v, prefix=prefix)
@render_ajax(template='extra_attributes.html', method='get')
def extra_attributes(request, lexeme_id, pos, genders=None):
l = Lexeme.all_objects.get(pk=lexeme_id)
part_of_speech = PartOfSpeech.objects.get(symbol=pos)
if genders:
genders = Gender.objects.filter(id__in=genders)
return {
'forms': attribute_forms(
l, part_of_speech=part_of_speech, genders=genders),
}
@ajax(method='get')
def check_attributes(request, lexeme_id, pos, genders):
l = Lexeme.all_objects.get(pk=lexeme_id)
part_of_speech = PartOfSpeech.objects.get(symbol=pos)
if genders:
genders = Gender.objects.filter(id__in=genders)
attrs = list(
l.attributes(part_of_speech, genders).values_list('pk', flat=True))
return {'attrs': attrs}
@render_ajax(template='lexeme_edit_form.html', method='get')
def lexeme_edit_form(request, id):
to_return = {}
l = Lexeme.all_objects.get(pk=id) # bo może być świeżo utworzony
if not l.perm(request.user, 'view'):
raise AjaxError('access denied')
editable = l.perm(request.user, 'change')
to_return['editable'] = editable
owner = l.owner_vocabulary
to_return['attribute_forms'] = attribute_forms(l)
editable_vocabs = editable_vocabularies(request.user)
ro_owner = owner not in editable_vocabs
to_return['multiple_editable'] = editable and editable_vocabs.count() > 1
if ro_owner:
# nie pokazujemy wszystkich, tylko te z właściciela
ro_qualifiers = l.qualifiers.filter(vocabulary=owner)
else:
ro_qualifiers = []
to_return['owner'] = owner
ro_vocabularies = l.visible_vocabularies(request.user).exclude(
pk=owner.pk).exclude(pk__in=editable_vocabs)
to_return['ro_vocabularies'] = ro_vocabularies
to_return['ro_qualifiers'] = ro_qualifiers
to_return['form'] = LexemeEditForm(
instance=l, editable=editable, user=request.user)
to_return['id'] = l.pk
to_return['part_of_speech'] = l.part_of_speech.symbol
to_return['classification_forms'] = make_classification_forms(
l, editable=editable)
lips = l.lexemeinflectionpattern_set.all()
to_return['lip_forms'] = [
(LIPEditForm(
part_of_speech=l.part_of_speech, instance=lip,
prefix='lip' + str(lip.pk), user=request.user, editable=editable),
lip.qualifiers.filter(vocabulary=owner) if ro_owner else [])
for lip in lips]
to_return['cross_references'] = l.cross_references(request.user)
if l.homonym_count(request.user) > 0:
to_return['homonym'] = l.homonym_number
return to_return
@ajax(method='get')
def check_classifications(request, owner_id, pos):
part_of_speech = PartOfSpeech.objects.get(symbol=pos)
owner = Vocabulary.objects.get(pk=owner_id)
classifications = owner.classifications.filter(
parts_of_speech=part_of_speech)
return {
'classifications': list(classifications.values_list('pk', flat=True))}
def make_classification_forms(lexeme, vocabulary=None, part_of_speech=None,
editable=True):
if not vocabulary:
vocabulary = lexeme.owner_vocabulary
if not part_of_speech:
part_of_speech = lexeme.part_of_speech
classifications = vocabulary.classifications.filter(
parts_of_speech=part_of_speech)
forms = []
for c in classifications:
values = lexeme.classification_values(c)
forms.append(
ClassificationForm(
classification=c, values=values, prefix='cl' + str(c.pk),
editable=editable))
return forms
@render_ajax(template='classification_forms.html', method='get')
def classification_forms(request, lexeme_id, vocab_id, pos):
l = Lexeme.all_objects.get(pk=lexeme_id)
part_of_speech = PartOfSpeech.objects.get(symbol=pos)
if vocab_id:
vocab = Vocabulary.objects.get(pk=vocab_id)
else:
vocab = None
forms = make_classification_forms(l, vocab, part_of_speech)
return {'classification_forms': forms}
@render_ajax(template='lexeme_edit_form_row.html', method='get')
def new_lip_edit_row(request, lexeme_id, pos_id, num):
l = Lexeme.all_objects.get(pk=lexeme_id)
if not l.perm(request.user, 'change'):
raise AjaxError('access denied')
if not pos_id:
raise AjaxError(u'Nieokreślona część mowy.')
pos = PartOfSpeech.objects.get(pk=pos_id)
lip_form = LIPEditForm(
part_of_speech=pos, prefix='lip_add_%s' % num, user=request.user)
return {'lip_form': lip_form, 'editable': True}
@render_ajax(template='cross_reference_row.html', method='get')
def new_cross_reference_row(request, id, pos_id, num):
l = Lexeme.all_objects.get(pk=id)
prefix = 'cr_add_%s' % num
if not l.perm(request.user, 'change'):
raise AjaxError('access denied')
pos = PartOfSpeech.objects.get(pk=pos_id)
cr_form = CrossReferenceForm(lexeme=l, pos=pos, prefix=prefix)
return {'cr_form': cr_form, 'editable': True}
def insert_new_lexeme(lexeme, request):
sort_rules = request.session['sort_rules']
query = LexemeQuery(
filter=request.session['filter'], sort_rules=sort_rules,
user=request.user)
id_list = query.get_id_list()
index = bisect_left(id_list, lexeme.entry, cmp=query.lexeme_cmp())
id_list.insert(index, lexeme.id)
key = query.cache_key()
cache.set(key, id_list)
@ajax(method='post')
def update_lexeme(request, form_data):
form_dict = dict((x['name'], x['value']) for x in form_data)
l = Lexeme.all_objects.get(pk=form_dict['id'])
if not l.perm(request.user, 'view'):
raise AjaxError('access denied')
owner = l.owner_vocabulary
new_lexeme = l.entry == ''
if not l.perm(request.user, 'change'):
return update_lexeme_qualifiers(
l, request.user, form_dict, form_data)
form = LexemeEditForm(data=form_dict, instance=l, user=request.user)
if form.is_valid():
l = form.save()
l.responsible = request.user
l.deleted = False
l.fix_homonym_number()
l.save()
else:
raise AjaxError(error_messages(form))
cand = l.status == Lexeme.STATUS_CANDIDATE
for vocab in editable_vocabularies(request.user):
if vocab != owner:
vocab.set_lexeme(l, vocab in form.cleaned_data['vocabularies'])
new_owner = form.cleaned_data.get('new_owner')
if new_owner and new_owner != owner:
l.change_owner(new_owner)
l.save()
for field_name in ('style_qualifiers', 'scope_qualifiers'):
for qualifier in form.fields[field_name].queryset:
qualifier.set_for(l, qualifier in form.cleaned_data[field_name])
classifications = l.owner_vocabulary.classifications.filter(
parts_of_speech=l.part_of_speech)
for c in classifications:
classification_form = ClassificationForm(
data=form_dict, classification=c, prefix='cl' + str(c.pk),
required=not cand)
if classification_form.is_valid():
values = classification_form.cleaned_data['values']
if values is None:
values = ()
cvs = ClassificationValue.objects.filter(pk__in=values)
l_cvs = l.classification_values(c)
for cv in l_cvs:
if cv.pk not in values:
cv.remove_lexeme(l)
for cv in cvs:
if cv not in l_cvs:
cv.add_lexeme(l)
else:
raise AjaxError(error_messages(classification_form))
for cv in l.classificationvalue_set.all():
if cv.classification not in classifications:
cv.remove_lexeme(l)
for prefix in form_dict['deleted']:
pk = int(prefix[3:])
LexemeInflectionPattern.objects.get(pk=pk).delete()
for cr_pk in form_dict['deleted_cr']:
CrossReference.objects.get(pk=cr_pk).delete()
submitted_lips = []
submitted_crs = []
for pair in form_data:
name = pair['name']
prefix = name.split('-')[0]
if name.startswith('lip') and prefix not in submitted_lips:
submitted_lips.append(prefix)
if prefix.startswith('lip_add'):
lip = LexemeInflectionPattern()
lip.lexeme = l
else:
pk = int(prefix[3:])
lip = LexemeInflectionPattern.objects.get(pk=pk)
form_dict[prefix + '-qualifiers'] = get_list(
form_data, prefix + '-qualifiers')
lip_form = LIPEditForm(
part_of_speech=l.part_of_speech, data=form_dict, prefix=prefix,
instance=lip, user=request.user, index=len(submitted_lips))
if lip_form.is_valid():
lip = lip_form.save()
lip.root = l.get_root(lip.pattern, lip.gender)
if lip.root is None:
raise AjaxError(
u'Niepasujące zakończenie formy podstawowej.')
for qualifier in lip_form.fields['qualifiers'].queryset:
qualifier.set_for(
lip, qualifier in lip_form.cleaned_data['qualifiers'])
lip.save()
else:
raise AjaxError(error_messages(lip_form))
if name.startswith('cr_add') and prefix not in submitted_crs:
submitted_crs.append(prefix)
cr_form = CrossReferenceForm(data=form_dict, prefix=prefix)
if cr_form.is_valid():
cr_form.save()
else:
raise AjaxError(error_messages(cr_form))
if len(submitted_lips) == 0 and l.status != Lexeme.STATUS_CANDIDATE:
raise AjaxError(u'Wybierz odmianę lub ustaw status "kandydat".')
extra_attrs = l.attributes()
for attr in extra_attrs:
attr_values = attr.values.filter(lexemes=l)
if not attr.multiple:
prefix = 'attr' + str(attr.pk)
assert len(attr_values) <= 1
if not attr.closed:
attr_form = LexemeOpenAttributeForm(
attribute=attr, data=form_dict, prefix=prefix)
else:
attr_form = LexemeClosedAttributeForm(
attribute=attr, data=form_dict, prefix=prefix,
required=not cand)
if attr_form.is_valid():
if not attr.closed:
value = attr_form.cleaned_data['value']
av, created = LexemeAttributeValue.objects.get_or_create(
attribute=attr, value=value)
else:
av = attr_form.cleaned_data['value']
if not attr_values or attr_values.get() != av:
for av1 in attr_values:
av1.remove_lexeme(l)
if av:
av.add_lexeme(l)
else:
raise AjaxError(error_messages(attr_form))
else:
prefix = 'attrmulti' + str(attr.pk)
attr_form = LexemeMultipleAttributeForm(
attribute=attr, data=form_dict, prefix=prefix,
required=not cand)
if attr_form.is_valid():
new_values = attr_form.cleaned_data['value']
if new_values is None:
new_values = ()
for av in set(attr_values) - set(new_values):
av.remove_lexeme(l)
for av in set(new_values) - set(attr_values):
av.add_lexeme(l)
else:
raise AjaxError(error_messages(attr_form))
for av in l.lexemeattributevalue_set.all():
if av.attribute not in extra_attrs:
av.remove_lexeme(l)
refresh_lexeme_data(l)
if new_lexeme:
insert_new_lexeme(l, request)
computed_derivatives = lexeme_derivatives(l)
crs = l.refs_to.values_list(
'to_lexeme__entry', 'to_lexeme__part_of_speech_id')
cr_set = set(tuple(cr) for cr in crs)
needed_derivatives = [
d for d in computed_derivatives if (d['entry'], d['pos']) not in cr_set]
return {'derivatives': needed_derivatives}
@ajax(method='post')
def create_derivatives(request, lexeme_id, chosen_derivatives):
lexeme = Lexeme.objects.get(id=lexeme_id)
new_derivatives = {}
for der_data in chosen_derivatives:
pos = der_data['pos']
entry = der_data['entry']
if entry == '':
raise AjaxError(u'Nie wpisano hasła')
new_lexemes = create_derivative(
lexeme, pos, entry, pl=der_data.get('pl'),
index=der_data['index'])
for der in new_lexemes:
insert_new_lexeme(der, request)
new_derivatives[pos] = new_lexemes
chosen_poses = [der_data['pos'] for der_data in chosen_derivatives]
if lexeme.part_of_speech_id == 'adj':
if 'adv' in chosen_poses and 'advcom' in chosen_poses:
adv = new_derivatives['adv'][0]
advcom = new_derivatives['advcom'][0]
adv.add_cross_reference(advcom, 'advcom')
advcom.add_cross_reference(adv, 'comadv')
return {}
def update_lexeme_qualifiers(lexeme, user, form_dict, form_data):
owner = lexeme.owner_vocabulary
editable_vocabs = editable_vocabularies(user).exclude(pk=owner.pk)
# l_editable_vocabs = lexeme.editable_vocabularies(user)
l_editable_vocabs = editable_vocabularies(user)
qualifiers = Qualifier.objects.filter(vocabulary__in=l_editable_vocabs)
for qualifier in qualifiers:
qualifier.set_for(
lexeme, unicode(qualifier.pk) in form_dict.get('qualifiers', ()))
for vocab in editable_vocabs:
vocab.set_lexeme(lexeme, vocab.pk in form_dict['vocabularies'])
submitted_lips = []
for pair in form_data:
name = pair['name']
prefix = name.split('-')[0]
if name.startswith('lip') and prefix not in submitted_lips:
submitted_lips.append(prefix)
pk = int(prefix[3:])
lip = LexemeInflectionPattern.objects.get(pk=pk)
lip_qualifiers = get_list(form_data, prefix + '-qualifiers')
for qualifier in qualifiers:
qualifier.set_for(lip, unicode(qualifier.pk) in lip_qualifiers)
return {}
def get_list(form_data, name):
return [pair['value'] for pair in form_data if pair['name'] == name]
@ajax(method='post')
def delete_lexeme(request, lexeme_id):
lexeme_id = int(lexeme_id)
l = Lexeme.all_objects.get(pk=lexeme_id)
if not l.perm(request.user, 'change'):
raise AjaxError('access denied')
if not l.deleted:
l.deleted = True
l.save()
key_list = cache.get('key_list', [])
for key in key_list:
pk_list = cache.get(key)
if pk_list and lexeme_id in pk_list:
pk_list.remove(lexeme_id)
cache.set(key, pk_list)
return {}
@ajax(method='get')
def check_pos(request, pos_id, had_gender):
if (pos_id in ('subst', 'skrs', 'osc')) == had_gender:
return {'answer': 'yes'}
else:
return {'answer': 'no'}
@ajax(method='get')
def check_pattern(request, pattern_name, gender_id):
lips = LexemeInflectionPattern.objects.filter(
gender_id=gender_id, pattern__name=pattern_name)
lips = lips.exclude(lexeme__status=Lexeme.STATUS_CANDIDATE)
if lips.exists():
return {'answer': 'yes'}
else:
return {'answer': 'no'}
START_ID = 1000000
@ajax(method='post')
def create_lexeme(request):
owner = request.user.usersettings.default_owner
if not owner:
editable = editable_vocabularies(request.user)
if len(editable) == 1:
owner = editable[0]
pos_id = request.user.usersettings.default_pos_id or 'subst'
if request.user not in owner.all_editors():
raise AjaxError('access denied')
next_id = Lexeme.all_objects.filter(
pk__gte=START_ID).aggregate(Max('id'))['id__max']
next_id = next_id + 1 if next_id else START_ID
l = Lexeme.objects.create(
id=next_id, part_of_speech_id=pos_id,
owner_vocabulary=owner, status=Lexeme.STATUS_CANDIDATE,
responsible=request.user, deleted=True)
owner.add_lexeme(l)
return {'id': l.id}
@ajax(method='post')
def clone_lexeme(request, lexeme_id):
lexeme = Lexeme.objects.get(id=lexeme_id)
owner = request.user.usersettings.default_owner
next_id = Lexeme.all_objects.filter(
pk__gte=START_ID).aggregate(Max('id'))['id__max']
next_id = next_id + 1 if next_id else START_ID
comment = u'Leksem sklonowany %s' % (format_date(datetime.datetime.now()))
new_lexeme = Lexeme.objects.create(
id=next_id, part_of_speech_id=lexeme.part_of_speech_id,
entry=lexeme.entry, pronunciation=lexeme.pronunciation,
valence=lexeme.valence, source=lexeme.source,
borrowing_source_id=lexeme.borrowing_source_id, note=lexeme.note,
extended_note=lexeme.extended_note, specialist=lexeme.specialist,
status=lexeme.status, comment=comment,
owner_vocabulary_id=owner, responsible=request.user)
owner.add_lexeme(new_lexeme)
new_lexeme.fix_homonym_number() # nie zadziałał :/
new_lexeme.save()
new_lexeme.qualifiers = lexeme.qualifiers.all()
for lip in lexeme.lexemeinflectionpattern_set.all():
new_lip = LexemeInflectionPattern.objects.create(
lexeme=new_lexeme, index=lip.index, pattern=lip.pattern,
gender=lip.gender, root=lip.root)
new_lip.qualifiers = lip.qualifiers.all()
for lav in lexeme.lexemeav_set.all():
LexemeAV.objects.create(
lexeme=new_lexeme, attribute_value=lav.attribute_value)
for lcv in lexeme.lexemecv_set.all():
LexemeCV.objects.create(
lexeme=new_lexeme, classification_value=lcv.classification_value)
refresh_lexeme_data(new_lexeme)
insert_new_lexeme(new_lexeme, request)
return {'new_id': new_lexeme.id}
@ajax(method='get', login_required=True)
def homonym_count(request, entry, lexeme_id):
lexeme = Lexeme.all_objects.get(id=lexeme_id)
lexeme.entry = entry
return {'count': lexeme.homonym_count(request.user)}
@ajax(method='get', login_required=True)
def cr_homonyms(request, entry, cr_type):
cr_type = CrossReferenceType.objects.get(pk=cr_type)
pos = cr_type.to_pos
visible_vocabs = visible_qualifiers(request.user)
lexemes = Lexeme.objects.filter(
entry=entry, part_of_speech=pos, owner_vocabulary__in=visible_vocabs)
aspect = LexemeAttribute.objects.get(name=u'aspekt')
if pos in aspect.parts_of_speech.all():
labels = (u'Nr hom.', u'Aspekt', u'Wzór')
aspect = LexemeAttribute.objects.get(name=u'aspekt')
make_row = lambda lexeme, lip_data: (
lexeme.homonym_number,
lexeme.attribute_value(aspect).value
if lexeme.attribute_value(aspect) else '',
lip_data['patterns'])
elif pos.lexical_class_id == 'subst':
labels = (u'Nr hom.', u'Rodzaj', u'Wzór')
make_row = lambda lexeme, lip_data: (
lexeme.homonym_number, lip_data['genders'], lip_data['patterns'])
else:
labels = (u'Nr hom.', u'Wzór')
make_row = lambda lexeme, lip_data: (
lexeme.homonym_number, lip_data['patterns'])
lexemes_data = [
make_row(l, l.lip_data()) for l in lexemes.order_by('homonym_number')
]
return {'labels': labels, 'lexemes': lexemes_data}
@ajax(template='new_action_row.html', method='get', login_required=True)
def new_action_row(request, num):
form = ActionFieldForm(prefix='action_%s' % num)
return {'form': form}
@ajax(method='get', login_required=True)
def dynamic_action_fields(request, field_name):
action_form, value_form = dict(ACTION_FIELDS)[field_name][1:3]
return {
'action': action_form()['action'].as_widget(),
'value': value_form(request)['value'].as_widget(),
}
@ajax(method='post', login_required=True)
def execute_group_actions(request, actions, filter):
if not request.user.has_perm('dictionary.change_lexeme'):
raise AjaxError('access denied')
query = LexemeQuery(filter=filter, sort_rules=[], user=request.user)
pk_list = query.get_id_list()
lexemes = Lexeme.objects.filter(pk__in=pk_list)
for l in lexemes:
for action in actions:
field = action['field']
if field == 'status':
# action['type'] == 'set'
l.status = action['value']
elif field == 'using_vocabulary':
vocab = Vocabulary.objects.get(pk=action['value'])
if action['type'] == 'add':
vocab.add_lexeme(l)
else: # 'remove'
if vocab != l.owner_vocabulary:
vocab.remove_lexeme(l)
else: # field == 'lexeme_qualifier'
qual = Qualifier.objects.get(pk=action['value'])
# a co jeśli koliduje z innym?
if action['type'] == 'add':
l.qualifiers.add(qual) # add
else:
l.qualifiers.remove(qual) # add
l.save()
return {}
@ajax(method='post')
def save_columns(request, columns):
request.session['columns'] = columns
return {}
@ajax(method='post')
def add_vocabulary(request, name):
if not request.user.has_perm('dictionary.manage_vocabulary'):
raise AjaxError('access denied')
vocab = Vocabulary.objects.create(id=name)
vocab.managers.add(request.user) # add
vocab.viewers.add(request.user)
vocab.editors.add(request.user)
try:
posp = Classification.objects.get(name=u'pospolitość')
posp.vocabularies.add(vocab)
except Classification.DoesNotExist:
pass
return {}
# nieużywane
@ajax(method='get')
def vocabulary_permissions(request, vocab_id):
if not request.user.has_perm('dictionary.manage_vocabulary'):
raise AjaxError('access denied')
vocab = Vocabulary.objects.get(id=vocab_id)
return {
'managers': list(vocab.all_managers().values_list('pk', flat=True)),
'viewers': list(vocab.all_viewers().values_list('pk', flat=True)),
'editors': list(vocab.editors.values_list('pk', flat=True)),
}
@ajax(method='post')
def set_vocabulary_permission(request, name, user_id, perm, on):
if not request.user.has_perm('dictionary.manage_vocabulary'):
raise AjaxError('access denied')
vocab = Vocabulary.objects.get(id=name)
user = User.objects.get(pk=user_id)
if perm == 'view':
related_manager = vocab.viewers
elif perm == 'change':
related_manager = vocab.editors
else: # type == 'manage'
related_manager = vocab.managers
if on:
related_manager.add(user) # add
else:
related_manager.remove(user) # add
return {}