Coverage for app/venv/lib/python3.14/site-packages/weblate/glossary/views.py: 31%

46 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-07 07:15 +0000

1# Copyright © Michal Čihař <michal@weblate.org> 

2# 

3# SPDX-License-Identifier: GPL-3.0-or-later 

4from __future__ import annotations 

5 

6from typing import TYPE_CHECKING 

7 

8from django.contrib.auth.decorators import login_required 

9from django.http import JsonResponse 

10from django.shortcuts import get_object_or_404 

11from django.template.loader import render_to_string 

12from django.views.decorators.http import require_POST 

13 

14from weblate.glossary.forms import TermForm 

15from weblate.glossary.models import get_glossary_terms 

16from weblate.trans.models import Unit 

17from weblate.utils.ratelimit import session_ratelimit_post 

18from weblate.utils.views import get_form_errors 

19 

20if TYPE_CHECKING: 20 ↛ 21line 20 didn't jump to line 21 because the condition on line 20 was never true

21 from weblate.auth.models import AuthenticatedHttpRequest 

22 

23 

24@require_POST 

25@login_required 

26@session_ratelimit_post("glossary") 

27def add_glossary_term(request: AuthenticatedHttpRequest, unit_id): 

28 unit = get_object_or_404(Unit, pk=int(unit_id)) 

29 component = unit.translation.component 

30 user = request.user 

31 user.check_access_component(component) 

32 

33 code = 403 

34 results = "" 

35 details = "" 

36 terms = [] 

37 

38 if user.has_perm("glossary.add", component.project): 

39 form = TermForm(unit, user, request.POST) 

40 if form.is_valid(): 

41 translation = form.cleaned_data["translation"] 

42 added = translation.add_unit(request, **form.as_kwargs()) 

43 terms = form.cleaned_data["terms"] 

44 # Only append the new term if it's not already in the list 

45 if added.pk not in terms: 

46 terms.append(added.pk) 

47 code = 200 

48 

49 # Fetch matching terms 

50 all_terms = get_glossary_terms(unit, full=True) 

51 

52 # Create a set of existing term IDs 

53 existing_term_ids = {term.pk for term in all_terms} 

54 

55 # Add newly added term if not already present 

56 if added.pk not in existing_term_ids: 

57 all_terms.append(added) 

58 existing_term_ids.add(added.pk) 

59 

60 # Add any missing terms that aren't already present 

61 missing_terms = set(terms) - existing_term_ids 

62 if missing_terms: 

63 all_terms.extend(translation.unit_set.filter(pk__in=missing_terms)) 

64 

65 results = render_to_string( 

66 "snippets/glossary.html", 

67 { 

68 "glossary": all_terms, 

69 "unit": unit, 

70 "user": user, 

71 }, 

72 ) 

73 else: 

74 details = "\n".join(get_form_errors(form)) 

75 

76 return JsonResponse( 

77 data={ 

78 "responseCode": code, 

79 "responseDetails": details, 

80 "results": results, 

81 "terms": ",".join(str(x) for x in terms), 

82 } 

83 )