def file_uploaded(sender, oldstats, user, newstats, archive, **kwargs): if sender.is_template_project: # add template news to project instead of translation project directory = sender.project.directory else: directory = sender.directory if oldstats == newstats: logging.debug("file uploaded but stats didn't change") return if archive: message = '<a href="%s">%s</a> uploaded an archive to <a href="%s">%s</a> <br />' % ( get_profile(user).get_absolute_url(), user.username, sender.get_absolute_url(), sender.fullname, ) else: message = '<a href="%s">%s</a> uploaded a file to <a href="%s">%s</a> <br />' % ( get_profile(user).get_absolute_url(), user.username, sender.get_absolute_url(), sender.fullname, ) message += stats_message("Before upload", oldstats) + " <br />" message += stats_message("After upload", newstats) + " <br />" new_object(True, message, directory)
def reject_suggestion(request, uid, suggid): unit = get_object_or_404(Unit, id=uid) directory = unit.store.parent translation_project = unit.store.translation_project response = { 'udbid': unit.id, 'sugid': suggid, } if request.POST.get('reject'): try: sugg = unit.suggestion_set.get(id=suggid) except ObjectDoesNotExist: sugg = None profile = get_profile(request.user) if not check_profile_permission(profile, 'review', directory) and \ (not request.user.is_authenticated() or sugg and sugg.user != profile): raise PermissionDenied response['success'] = unit.reject_suggestion(suggid) if sugg is not None and response['success']: #FIXME: we need a totally different model for tracking stats, this is just lame suggstat, created = SuggestionStat.objects.get_or_create( translation_project=translation_project, suggester=sugg.user, state='pending', unit=unit.id) suggstat.reviewer = get_profile(request.user) suggstat.state = 'rejected' suggstat.save() response = simplejson.dumps(response) return HttpResponse(response, mimetype="application/json")
def reject_suggestion(request, uid, suggid): unit = get_object_or_404(Unit, id=uid) directory = unit.store.parent translation_project = unit.store.translation_project response = { 'udbid': unit.id, 'sugid': suggid, } if request.POST.get('reject'): try: sugg = unit.suggestion_set.get(id=suggid) except ObjectDoesNotExist: sugg = None profile = get_profile(request.user) if not check_profile_permission(profile, 'review', directory) and \ (not request.user.is_authenticated() or sugg and sugg.user != profile): raise PermissionDenied response['success'] = unit.reject_suggestion(suggid) if sugg is not None and response['success']: #FIXME: we need a totally different model for tracking stats, this is just lame suggstat, created = SuggestionStat.objects.get_or_create(translation_project=translation_project, suggester=sugg.user, state='pending', unit=unit.id) suggstat.reviewer = get_profile(request.user) suggstat.state = 'rejected' suggstat.save() response = simplejson.dumps(response) return HttpResponse(response, mimetype="application/json")
def file_uploaded(sender, oldstats, user, newstats, archive, **kwargs): if sender.is_template_project: # Add template news to project instead of translation project. directory = sender.project.directory else: directory = sender.directory if oldstats == newstats: logging.debug("file uploaded but stats didn't change") return args = { 'user_url': get_profile(user).get_absolute_url(), 'user': get_profile(user), 'sender_url': sender.get_absolute_url(), 'sender': sender.fullname, } if archive: message = ('<a href="%(user_url)s">%(user)s</a> uploaded an archive ' 'to <a href="%(sender_url)s">%(sender)s</a> <br />' % args) else: message = ('<a href="%(user_url)s">%(user)s</a> uploaded a file to ' '<a href="%(sender_url)s">%(sender)s</a> <br />' % args) old_total = oldstats["total"] new_total = newstats["total"] old_translated = oldstats["translated"] new_translated = newstats["translated"] old_fuzzy = oldstats["fuzzy"] new_fuzzy = newstats["fuzzy"] message += stats_message_raw('Before upload', old_total, old_translated, old_fuzzy) + ' <br />' message += stats_message_raw('After upload', new_total, new_translated, new_fuzzy) + ' <br />' new_object(True, message, directory)
def file_uploaded(sender, oldstats, user, newstats, archive, **kwargs): if sender.is_template_project: # add template news to project instead of translation project directory = sender.project.directory else: directory = sender.directory if oldstats == newstats: logging.debug("file uploaded but stats didn't change") return args = { 'user_url': get_profile(user).get_absolute_url(), 'user': get_profile(user), 'sender_url': sender.get_absolute_url(), 'sender': sender.fullname, } if archive: message = ('<a href="%(user_url)s">%(user)s</a> uploaded an archive ' 'to <a href="%(sender_url)s">%(sender)s</a> <br />' % args) else: message = ('<a href="%(user_url)s">%(user)s</a> uploaded a file to ' '<a href="%(sender_url)s">%(sender)s</a> <br />' % args) message += stats_message_raw('Before upload', oldstats) + ' <br />' message += stats_message_raw('After upload', newstats) + ' <br />' new_object(True, message, directory)
def accept_suggestion(request, uid, suggid): unit = get_object_or_404(Unit, id=uid) directory = unit.store.parent translation_project = unit.store.translation_project if not check_profile_permission( get_profile(request.user), 'review', directory): raise PermissionDenied response = { 'udbid': unit.id, 'sugid': suggid, } if request.POST.get('accept'): try: suggestion = unit.suggestion_set.get(id=suggid) except ObjectDoesNotExist: suggestion = None response['success'] = unit.accept_suggestion(suggid) response['newtargets'] = [ highlight_whitespace(target) for target in unit.target.strings] response['newdiffs'] = {} for sugg in unit.get_suggestions(): response['newdiffs'][sugg.id] = [ highlight_diffs(unit.target.strings[i], target) \ for i, target in enumerate(sugg.target.strings)] if suggestion is not None and response['success']: if suggestion.user: translation_submitted.send( sender=translation_project, unit=unit, profile=suggestion.user) # FIXME: we need a totally different model for tracking # stats, this is just lame suggstat, created = SuggestionStat.objects.get_or_create( translation_project=translation_project, suggester=suggestion.user, state='pending', unit=unit.id) suggstat.reviewer = get_profile(request.user) suggstat.state = 'accepted' suggstat.save() sub = Submission(translation_project=translation_project, submitter=get_profile(request.user), from_suggestion=suggstat) sub.save() response = simplejson.dumps(response) return HttpResponse(response, mimetype="application/json")
def accept_suggestion(request, uid, suggid): unit = get_object_or_404(Unit, id=uid) directory = unit.store.parent translation_project = unit.store.translation_project if not check_profile_permission(get_profile(request.user), 'review', directory): raise PermissionDenied response = { 'udbid': unit.id, 'sugid': suggid, } if request.POST.get('accept'): try: suggestion = unit.suggestion_set.get(id=suggid) except ObjectDoesNotExist: suggestion = None response['success'] = unit.accept_suggestion(suggid) response['newtargets'] = [ highlight_whitespace(target) for target in unit.target.strings ] response['newdiffs'] = {} for sugg in unit.get_suggestions(): response['newdiffs'][sugg.id] = [highlight_diffs(unit.target.strings[i], target) \ for i, target in enumerate(sugg.target.strings)] if suggestion is not None and response['success']: if suggestion.user: translation_submitted.send(sender=translation_project, unit=unit, profile=suggestion.user) #FIXME: we need a totally different model for tracking stats, this is just lame suggstat, created = SuggestionStat.objects.get_or_create( translation_project=translation_project, suggester=suggestion.user, state='pending', unit=unit.id) suggstat.reviewer = get_profile(request.user) suggstat.state = 'accepted' suggstat.save() sub = Submission(translation_project=translation_project, submitter=get_profile(request.user), from_suggestion=suggstat) sub.save() response = simplejson.dumps(response) return HttpResponse(response, mimetype="application/json")
def reject_qualitycheck(request, uid, checkid): json = {} try: unit = Unit.objects.get(id=uid) directory = unit.store.parent if not check_profile_permission(get_profile(request.user), 'review', directory): json["success"] = False json["msg"] = _("You do not have rights to access review mode.") else: json["udbid"] = uid json["checkid"] = checkid if request.POST.get('reject'): try: check = unit.qualitycheck_set.get(id=checkid) check.false_positive = True check.save() # update timestamp unit.save() json['success'] = True except ObjectDoesNotExist: check = None json['success'] = False json["msg"] = _("Check %(checkid)s does not exist." % {'checkid': checkid}) except Unit.DoesNotExist: json['success'] = False json["msg"] = _("Unit %(uid)s does not exist." % {'uid': uid}) response = simplejson.dumps(json) return HttpResponse(response, mimetype="application/json")
def reject_qualitycheck(request, uid, checkid): unit = get_object_or_404(Unit, id=uid) directory = unit.store.parent if not check_profile_permission( get_profile(request.user), 'review', directory): raise PermissionDenied response = { 'udbid': unit.id, 'checkid': checkid, } if request.POST.get('reject'): try: check = unit.qualitycheck_set.get(id=checkid) check.false_positive = True check.save() # update timestamp unit.save() response['success'] = True except ObjectDoesNotExist: check = None response['success'] = False response = simplejson.dumps(response) return HttpResponse(response, mimetype="application/json")
def GET(self, template_vars, request, translation_project, directory): template_vars = super(TPTranslateView, self).GET(template_vars, request) request.permissions = get_matching_permissions( get_profile(request.user), translation_project.directory) project = translation_project.project language = translation_project.language template_vars.update({ 'translation_project': translation_project, 'project': project, 'language': language, 'directory': directory, 'children': get_children(request, translation_project, directory, links_required='translate'), 'navitems': [ navbar_dict.make_directory_navbar_dict( request, directory, links_required='translate') ], 'feed_path': directory.pootle_path[1:], 'topstats': gentopstats_translation_project(translation_project), }) return template_vars
def GET(self, template_vars, request, translation_project, directory): template_vars = super(ProjectIndexView, self).GET(template_vars, request) request.permissions = get_matching_permissions( get_profile(request.user), translation_project.directory) state = dispatch.ProjectIndexState(request.GET) project = translation_project.project language = translation_project.language template_vars.update({ 'translation_project': translation_project, 'project': project, 'language': language, 'directory': directory, 'children': get_children(request, translation_project, directory), 'navitems': [navbar_dict.make_directory_navbar_dict(request, directory)], 'stats_headings': get_stats_headings(), 'editing': state.editing, 'topstats': gentopstats_translation_project(translation_project), 'feed_path': directory.pootle_path[1:], }) return template_vars
def get_view_units(request, pootle_path, limit=0): """ @return: An object in JSON notation that contains the source and target texts for units that will be displayed before and after unit C{uid}. Success status that indicates if the unit has been succesfully retrieved or not is returned as well. """ if pootle_path[0] != '/': pootle_path = '/' + pootle_path profile = get_profile(request.user) json = {} page = request.GET.get('page', 1) try: store = Store.objects.select_related('translation_project', 'parent').get(pootle_path=pootle_path) if not check_profile_permission(profile, 'view', store.parent): json["success"] = False json["msg"] = _("You do not have rights to access translation mode.") else: if not limit: limit = profile.get_unit_rows() units_qs = _filter_queryset(request.GET, store.units) json["units"] = _filter_view_units(units_qs, int(page), int(limit)) json["success"] = True except Store.DoesNotExist: json["success"] = False json["msg"] = _("Store %(path)s does not exist." % {'path': pootle_path}) response = simplejson.dumps(json) return HttpResponse(response, mimetype="application/json")
def get_current_units(request, step_queryset, units_queryset): """returns current active unit, and in case of POST previously active unit""" edit_unit = None prev_unit = None pager = None # GET gets priority if 'unit' in request.GET: # load a specific unit in GET try: edit_id = int(request.GET['unit']) edit_unit = step_queryset.get(id=edit_id) except (Unit.DoesNotExist, ValueError): pass elif 'page' in request.GET: # load first unit in a specific page profile = get_profile(request.user) unit_rows = profile.get_unit_rows() pager = paginate(request, units_queryset, items=unit_rows) edit_unit = pager.object_list[0] elif 'id' in request.POST and 'index' in request.POST: # GET doesn't specify a unit try POST prev_id = int(request.POST['id']) prev_index = int(request.POST['index']) pootle_path = request.POST['pootle_path'] back = request.POST.get('back', False) if back: queryset = (step_queryset.filter(store__pootle_path=pootle_path, index__lte=prev_index) | \ step_queryset.filter(store__pootle_path__lt=pootle_path) ).order_by('-store__pootle_path', '-index') else: queryset = (step_queryset.filter(store__pootle_path=pootle_path, index__gte=prev_index) | \ step_queryset.filter(store__pootle_path__gt=pootle_path) ).order_by('store__pootle_path', 'index') for unit in queryset.iterator(): if edit_unit is None and prev_unit is not None: edit_unit = unit break if unit.id == prev_id: prev_unit = unit elif unit.index > prev_index or back and unit.index < prev_index: logging.debug("submitting to a unit no longer part of step query, %s:%d", (pootle_path, prev_id)) # prev_unit no longer part of the query, load it directly edit_unit = unit prev_unit = Unit.objects.get(store__pootle_path=pootle_path, id=prev_id) break if edit_unit is None: if prev_unit is not None: # probably prev_unit was last unit in chain. if back: edit_unit = prev_unit else: # all methods failed, get first unit in queryset try: edit_unit = step_queryset.iterator().next() except StopIteration: pass return prev_unit, edit_unit, pager
def get_view_units(request, pootle_path, limit=0): """ @return: An object in JSON notation that contains the source and target texts for units that will be displayed before and after unit C{uid}. Success status that indicates if the unit has been succesfully retrieved or not is returned as well. """ if pootle_path[0] != '/': pootle_path = '/' + pootle_path profile = get_profile(request.user) json = {} page = request.GET.get('page', 1) try: store = Store.objects.select_related( 'translation_project', 'parent').get(pootle_path=pootle_path) if not check_profile_permission(profile, 'view', store.parent): json["success"] = False json["msg"] = _( "You do not have rights to access translation mode.") else: if not limit: limit = profile.get_unit_rows() units_qs = _filter_queryset(request.GET, store.units) json["units"] = _filter_view_units(units_qs, int(page), int(limit)) json["success"] = True except Store.DoesNotExist: json["success"] = False json["msg"] = _("Store %(path)s does not exist." % {'path': pootle_path}) response = simplejson.dumps(json) return HttpResponse(response, mimetype="application/json")
def create_notice(creator, message, directory): profile = get_profile(creator) if not check_profile_permission(profile, 'administrate', directory): raise PermissionDenied new_notice = Notice(directory=directory, message=message) new_notice.save() return new_notice
def _handle_upload_form(request, translation_project): """Process the upload form in TP overview.""" from pootle_app.models.signals import post_file_upload upload_form_class = upload_form_factory(request) if request.method == 'POST' and 'file' in request.FILES: upload_form = upload_form_class(request.POST, request.FILES) if not upload_form.is_valid(): return upload_form else: django_file = upload_form.cleaned_data['file'] overwrite = upload_form.cleaned_data['overwrite'] upload_to = upload_form.cleaned_data['upload_to'] upload_to_dir = upload_form.cleaned_data['upload_to_dir'] # XXX Why do we scan here? translation_project.scan_files(vcs_sync=False) oldstats = translation_project.get_stats() # The URL relative to the URL of the translation project. Thus, if # directory.pootle_path == /af/pootle/foo/bar, then # relative_root_dir == foo/bar. if django_file.name.endswith('.zip'): archive = True target_directory = upload_to_dir or request.directory upload_archive(request, target_directory, django_file, overwrite) else: archive = False upload_file(request, request.directory, django_file, overwrite, store=upload_to) translation_project.scan_files(vcs_sync=False) newstats = translation_project.get_stats() # Create a submission. Doesn't fix stats but at least shows up in # last activity column. from django.utils import timezone s = Submission( creation_time=timezone.now(), translation_project=translation_project, submitter=get_profile(request.user), type=SubmissionTypes.UPLOAD, # The other fields are only relevant to unit-based changes. ) s.save() post_file_upload.send(sender=translation_project, user=request.user, oldstats=oldstats, newstats=newstats, archive=archive) # Always return a blank upload form unless the upload form is not valid. return upload_form_class()
def _wrapped(request, *args, **kwargs): path_obj = args[0] directory = (path_obj if isinstance(path_obj, Directory) else path_obj.directory) # HACKISH: some old code relies on `request.translation_project`, # `request.language` etc. being set, so we need to set that too. attr_name = CLS2ATTR.get(path_obj.__class__.__name__, 'path_obj') setattr(request, attr_name, path_obj) request.profile = get_profile(request.user) request.permissions = get_matching_permissions(request.profile, directory) if not permission_codes: return func(request, *args, **kwargs) permission_codes_list = permission_codes if isinstance(permission_codes, basestring): permission_codes_list = [permission_codes] for permission_code in permission_codes_list: if not check_permission(permission_code, request): raise PermissionDenied( _("Insufficient rights to access this page."), ) return func(request, *args, **kwargs)
def decorated_f(request, translation_project, *args, **kwargs): # For now, all permissions in a translation project are # relative to the root of that translation project. request.permissions = get_matching_permissions( get_profile(request.user), translation_project.directory) request.translation_project = translation_project return f(request, translation_project, *args, **kwargs)
def process_request(self, request): path_fragments = filter(None, request.path.split('/')) path_length = len(path_fragments) context = {} # Language if path_length > 0 and path_fragments[0] not in ['admin', 'accounts', 'projects'] and not path_fragments[0].endswith('.html'): try: context['language'] = Language.objects.get(code=path_fragments[0]) except Language.DoesNotExist: pass # Project if path_length > 1 and ('language' in context or path_fragments[0] == 'projects'): try: context['project'] = Project.objects.get(code=path_fragments[1]) except Project.DoesNotExist: pass # TranslationProject if 'language' in context and 'project' in context: try: context['translation_project'] = TranslationProject.objects.get( language=context['language'], project=context['project']) except TranslationProject.DoesNotExist: pass request.pootle_context = context request.profile = get_profile(request.user)
def view(request, path): # FIXME: why do we have leading and trailing slashes in pootle_path? pootle_path = "/%s" % path directory = get_object_or_404(Directory, pootle_path=pootle_path) request.permissions = get_matching_permissions(get_profile(request.user), directory) if not check_permission("view", request): raise PermissionDenied template_vars = {"path": path, "directory": directory} if check_permission("administrate", request): template_vars["form"] = handle_form(request, directory) template_vars["title"] = directory_to_title(directory) if request.GET.get("all", False): template_vars["notices"] = Notice.objects.filter( directory__pootle_path__startswith=directory.pootle_path ).select_related("directory")[:30] else: template_vars["notices"] = Notice.objects.filter(directory=directory).select_related("directory")[:30] if not directory.is_language() and not directory.is_project(): try: request.translation_project = directory.get_translationproject() template_vars["navitems"] = [navbar_dict.make_directory_navbar_dict(request, directory)] template_vars["translation_project"] = request.translation_project template_vars["language"] = request.translation_project.language template_vars["project"] = request.translation_project.project except: pass return render_to_response("notices.html", template_vars, context_instance=RequestContext(request))
def language_index(request, language_code): language = get_object_or_404(Language, code=language_code) request.permissions = get_matching_permissions(get_profile(request.user), language.directory) if not check_permission("view", request): raise PermissionDenied projects = language.translationproject_set.order_by('project__fullname') projectcount = len(projects) items = (make_project_item(translate_project) for translate_project in projects.iterator()) totals = language.getquickstats() average = nice_percentage(totals['translatedsourcewords'] * 100.0 / max(totals['totalsourcewords'], 1)) topstats = gentopstats_language(language) templatevars = { 'language': { 'code': language.code, 'name': tr_lang(language.fullname), 'stats': ungettext('%(projects)d project, %(average)d%% translated', '%(projects)d projects, %(average)d%% translated', projectcount, {"projects": projectcount, "average": average}), }, 'feed_path': '%s/' % language.code, 'projects': items, 'statsheadings': get_stats_headings(), 'topstats': topstats, 'instancetitle': pagelayout.get_title(), } return render_to_response("language/language_index.html", templatevars, context_instance=RequestContext(request))
def tp_settings_edit(request, translation_project): request.permissions = get_matching_permissions( get_profile(request.user), translation_project.directory ) if not check_permission('administrate', request): raise PermissionDenied from pootle_translationproject.forms import DescriptionForm form = DescriptionForm(request.POST, instance=translation_project) response = {} if form.is_valid(): form.save() response = { "intro": form.cleaned_data['description'], "valid": True, } context = { "form": form, "form_action": translation_project.pootle_path + "edit_settings.html", } t = loader.get_template('admin/general_settings_form.html') c = RequestContext(request, context) response['form'] = t.render(c) return HttpResponse(jsonify(response), mimetype="application/json")
def projects_index(request): """page listing all projects""" request.permissions = get_matching_permissions(get_profile(request.user), Directory.objects.root) if not check_permission('view', request): raise PermissionDenied topstats = gentopstats_root() templatevars = { 'projects': getprojects(request), 'topstats': topstats, 'translationlegend': { 'translated': _('Translations are complete'), 'fuzzy': _('Translations need to be checked ' '(they are marked fuzzy)'), 'untranslated': _('Untranslated') }, } return render_to_response('project/projects.html', templatevars, RequestContext(request))
def project_settings_edit(request, project_code): project = get_object_or_404(Project, code=project_code) request.permissions = get_matching_permissions( get_profile(request.user), project.directory ) if not check_permission('administrate', request): raise PermissionDenied from pootle_project.forms import DescriptionForm form = DescriptionForm(request.POST, instance=project) response = {} if form.is_valid(): form.save() response = { "intro": form.cleaned_data['description'], "valid": True, } context = { "form": form, "form_action": project.pootle_path + "edit_settings.html", } t = loader.get_template('admin/general_settings_form.html') c = RequestContext(request, context) response['form'] = t.render(c) return HttpResponse(jsonify(response), mimetype="application/json")
def view(request, path): #FIXME: why do we have leading and trailing slashes in pootle_path? pootle_path = '/%s' % path directory = get_object_or_404(Directory, pootle_path=pootle_path) request.permissions = get_matching_permissions(get_profile(request.user), directory) if not check_permission('view', request): raise PermissionDenied template_vars = {'path': path, 'directory': directory} if check_permission('administrate', request): template_vars['form'] = handle_form(request, directory) template_vars['title'] = directory_to_title(request, directory) if request.GET.get('all', False): template_vars['notices'] = Notice.objects.filter(directory__pootle_path__startswith=directory.pootle_path).select_related('directory')[:30] else: template_vars['notices'] = Notice.objects.filter(directory=directory).select_related('directory')[:30] if not directory.is_language() and not directory.is_project(): try: request.translation_project = directory.get_translationproject() template_vars['navitems'] = [navbar_dict.make_directory_navbar_dict(request, directory)] template_vars['translation_project'] = request.translation_project template_vars['language'] = request.translation_project.language template_vars['project'] = request.translation_project.project except: pass return render_to_response('notices.html', template_vars, context_instance=RequestContext(request))
def process_request(self, request): path_fragments = filter(None, request.path.split('/')) path_length = len(path_fragments) context = {} # Language if path_length > 0 and path_fragments[0] not in [ 'admin', 'accounts', 'projects' ] and not path_fragments[0].endswith('.html'): try: context['language'] = Language.objects.get( code=path_fragments[0]) except Language.DoesNotExist: pass # Project if path_length > 1 and ('language' in context or path_fragments[0] == 'projects'): try: context['project'] = Project.objects.get( code=path_fragments[1]) except Project.DoesNotExist: pass # TranslationProject if 'language' in context and 'project' in context: try: context[ 'translation_project'] = TranslationProject.objects.get( language=context['language'], project=context['project']) except TranslationProject.DoesNotExist: pass request.pootle_context = context request.profile = get_profile(request.user)
def user_joined_language(sender, instance, action, reverse, model, pk_set, **kwargs): if action == 'post_add' and not reverse: for project in instance.languages.filter(pk__in=pk_set).iterator(): message = 'User <a href="%s">%s</a> joined language <a href="%s">%s</a>' % ( instance.get_absolute_url(), get_profile(user), project.get_absolute_url(), project.fullname) new_object(True, message, project.directory)
def GET(self, template_vars, request, translation_project, directory): template_vars = super(TPReviewView, self).GET(template_vars, request) request.permissions = get_matching_permissions( get_profile(request.user), translation_project.directory) project = translation_project.project language = translation_project.language is_terminology = project.is_terminology children = get_children(request, translation_project, directory, links_required='review') navitems = [navbar_dict.make_directory_navbar_dict( request, directory, links_required='review', terminology=is_terminology)] template_vars.update({ 'translation_project': translation_project, 'project': project, 'language': language, 'directory': directory, 'children': children, 'navitems': navitems, 'topstats': gentopstats_translation_project(translation_project), 'feed_path': directory.pootle_path[1:], }) return template_vars
def _wrapped(request, *args, **kwargs): path_obj = args[0] directory = (path_obj if isinstance(path_obj, Directory) else path_obj.directory) # HACKISH: some old code relies on `request.translation_project`, # `request.language` etc. being set, so we need to set that too. attr_name = CLS2ATTR.get(path_obj.__class__.__name__, 'path_obj') setattr(request, attr_name, path_obj) request.profile = get_profile(request.user) request.permissions = get_matching_permissions( request.profile, directory) if not permission_codes: return func(request, *args, **kwargs) permission_codes_list = permission_codes if isinstance(permission_codes, basestring): permission_codes_list = [permission_codes] for permission_code in permission_codes_list: if not check_permission(permission_code, request): raise PermissionDenied( _("Insufficient rights to access this page."), ) return func(request, *args, **kwargs)
def view(request): request.permissions = get_matching_permissions(get_profile(request.user), Directory.objects.root) topstats = gentopstats_root() templatevars = { "description": pagelayout.get_description(), "keywords": [ "Pootle", "translate", "translation", "localisation", "localization", "l10n", "traduction", "traduire", ], "languagelink": _("Languages"), "languages": getlanguages(request), "projectlink": _("Projects"), "projects": getprojects(request), "topstats": topstats, "instancetitle": pagelayout.get_title(), "translationlegend": { "translated": _("Translations are complete"), "fuzzy": _("Translations need to be checked (they are marked fuzzy)"), "untranslated": _("Untranslated"), }, "permissions": request.permissions, } visible_langs = [l for l in templatevars["languages"] if l["total"] != 0] templatevars["moreprojects"] = len(templatevars["projects"]) > len(visible_langs) return render_to_response("index/index.html", templatevars, RequestContext(request))
def GET(self, template_vars, request, translation_project, directory): user_profile = get_profile(request.user) tp_dir = translation_project.directory project = translation_project.project language = translation_project.language is_terminology = project.is_terminology description = translation_project.description directory_stats = get_raw_stats(directory) directory_summary = get_directory_summary(directory, directory_stats) template_vars.update({ 'translation_project': translation_project, 'description': description, 'project': project, 'language': language, 'directory': directory, 'children': get_children(request, translation_project, directory), 'dir_summary': directory_summary, 'stats': directory_stats, 'stats_headings': get_stats_headings(), 'topstats': gentopstats_translation_project(translation_project), 'feed_path': directory.pootle_path[1:], }) if check_permission('administrate', request): from pootle_translationproject.forms import DescriptionForm template_vars['form'] = DescriptionForm(instance=translation_project) return template_vars
def committed_to_version_control(sender, store, stats, user, success, **kwargs): message = '<a href="%s">%s</a> committed <a href="%s">%s</a> to version control' % ( user.get_absolute_url(), get_profile(user), store.get_absolute_url(), store.pootle_path) message = stats_message_raw(message, stats) new_object(success, message, sender.directory)
def view(request): request.permissions = get_matching_permissions(get_profile(request.user), Directory.objects.root) topstats = gentopstats_root() templatevars = { 'description': pagelayout.get_description(), 'keywords': [ 'Pootle', 'translate', 'translation', 'localisation', 'localization', 'l10n', 'traduction', 'traduire', ], 'languagelink': _('Languages'), 'languages': getlanguages(request), 'projectlink': _('Projects'), 'projects': getprojects(request), 'projectstypo3typo3core': getprojectstypo3typo3core(request), 'projectstypo3typo3ext': getprojectstypo3typo3ext(request), 'topstats': topstats, 'instancetitle': pagelayout.get_title(), 'translationlegend': {'translated': _('Translations are complete'), 'fuzzy': _('Translations need to be checked (they are marked fuzzy)'), 'untranslated': _('Untranslated')}, 'permissions': request.permissions, } visible_langs = [l for l in templatevars['languages'] if l['total'] != 0] templatevars['moreprojects'] = len(templatevars['projects']) >\ len(visible_langs) return render_to_response('index/index.html', templatevars, RequestContext(request))
def project_language_index(request, project_code): """page listing all languages added to project""" project = get_object_or_404(Project, code=project_code) request.permissions = get_matching_permissions(get_profile(request.user), project.directory) if not check_permission('view', request): raise PermissionDenied translation_projects = project.translationproject_set.all() items = [make_language_item(request, translation_project) for translation_project in translation_projects.iterator()] items.sort(lambda x, y: locale.strcoll(x['title'], y['title'])) languagecount = len(translation_projects) totals = add_percentages(project.getquickstats()) average = totals['translatedpercentage'] topstats = gentopstats_project(project) templatevars = { 'project': { 'code': project.code, 'name': project.fullname, 'stats': ungettext('%(languages)d language, %(average)d%% translated', '%(languages)d languages, %(average)d%% translated', languagecount, {"languages": languagecount, "average": average}), }, 'description': project.description, 'adminlink': _('Admin'), 'languages': items, 'instancetitle': pagelayout.get_title(), 'topstats': topstats, 'statsheadings': get_stats_headings(), 'translationlegend': {'translated': _('Translations are complete'), 'fuzzy': _('Translations need to be checked (they are marked fuzzy)'), 'untranslated': _('Untranslated')}, } return render_to_response('project/project.html', templatevars, context_instance=RequestContext(request))
def do_upload(self, request, translation_project, directory): if self.form.is_valid() and 'file' in request.FILES: django_file = self.form.cleaned_data['file'] overwrite = self.form.cleaned_data['overwrite'] scan_translation_project_files(translation_project) oldstats = translation_project.getquickstats() # The URL relative to the URL of the translation project. Thus, if # directory.pootle_path == /af/pootle/foo/bar, then # relative_root_dir == foo/bar. if django_file.name.endswith('.zip'): archive = True upload_archive(request, directory, django_file, overwrite) else: archive = False upload_file(request, directory, django_file, overwrite) scan_translation_project_files(translation_project) newstats = translation_project.getquickstats() # create a submission, doesn't fix stats but at least # shows up in last activity column s = Submission(creation_time=datetime.datetime.utcnow(), translation_project=translation_project, submitter=get_profile(request.user)) s.save() post_file_upload.send(sender=translation_project, user=request.user, oldstats=oldstats, newstats=newstats, archive=archive) return {'upload': self}
def reject_qualitycheck(request, uid, checkid): unit = get_object_or_404(Unit, id=uid) directory = unit.store.parent if not check_profile_permission(get_profile(request.user), 'review', directory): raise PermissionDenied response = { 'udbid': unit.id, 'checkid': checkid, } if request.POST.get('reject'): try: check = unit.qualitycheck_set.get(id=checkid) check.false_positive = True check.save() # update timestamp unit.save() response['success'] = True except ObjectDoesNotExist: check = None response['success'] = False response = simplejson.dumps(response) return HttpResponse(response, mimetype="application/json")
def language_index(request, language_code): language = get_object_or_404(Language, code=language_code) request.permissions = get_matching_permissions(get_profile(request.user), language.directory) if not check_permission("view", request): raise PermissionDenied projects = language.translationproject_set.order_by('project__fullname') projectcount = len(projects) items = (make_project_item(translate_project) for translate_project in projects.iterator()) totals = language.getquickstats() average = nice_percentage(totals['translatedsourcewords'] * 100.0 / max(totals['totalsourcewords'], 1)) topstats = gentopstats_language(language) templatevars = { 'language': { 'code': language.code, 'name': tr_lang(language.fullname), 'description': language.description, 'stats': ungettext('%(projects)d project, %(average)d%% translated', '%(projects)d projects, %(average)d%% translated', projectcount, {"projects": projectcount, "average": average}), }, 'feed_path': '%s/' % language.code, 'description': language.description, 'projects': items, 'statsheadings': get_stats_headings(), 'topstats': topstats, } if check_permission('administrate', request): from pootle_language.forms import DescriptionForm templatevars['form'] = DescriptionForm(instance=language) return render_to_response("language/language_index.html", templatevars, context_instance=RequestContext(request))
def get_edit_unit(request, pootle_path, uid): """ Given a store path C{pootle_path} and unit id C{uid}, gathers all the necessary information to build the editing widget. @return: A templatised editing widget is returned within the C{editor} variable and paging information is also returned if the page number has changed. """ if pootle_path[0] != '/': pootle_path = '/' + pootle_path unit = get_object_or_404(Unit, id=uid, store__pootle_path=pootle_path) translation_project = unit.store.translation_project language = translation_project.language form_class = unit_form_factory(language, len(unit.source.strings)) form = form_class(instance=unit) store = unit.store directory = store.parent profile = get_profile(request.user) alt_src_langs = get_alt_src_langs(request, profile, translation_project) project = translation_project.project template_vars = {'unit': unit, 'form': form, 'store': store, 'profile': profile, 'user': request.user, 'language': language, 'source_language': translation_project.project.source_language, 'cantranslate': check_profile_permission(profile, "translate", directory), 'cansuggest': check_profile_permission(profile, "suggest", directory), 'canreview': check_profile_permission(profile, "review", directory), 'altsrcs': find_altsrcs(unit, alt_src_langs, store=store, project=project), 'suggestions': get_sugg_list(unit)} t = loader.get_template('unit/edit.html') c = RequestContext(request, template_vars) json = {'success': True, 'editor': t.render(c)} current_page = int(request.GET.get('page', 1)) all_units = unit.store.units units_qs = _filter_queryset(request.GET, all_units) unit_rows = profile.get_unit_rows() current_unit = unit if current_unit is not None: current_index = _get_index_in_qs(units_qs, current_unit) preceding = units_qs[:current_index].count() page = preceding / unit_rows + 1 if page != current_page: pager = paginate(request, units_qs, items=unit_rows, page=page) json["pager"] = _build_pager_dict(pager) # Return context rows if filtering is applied if 'filter' in request.GET and request.GET.get('filter', 'all') != 'all': edit_index = _get_index_in_qs(all_units, current_unit) json["ctxt"] = _filter_ctxt_units(all_units, edit_index, 2) response = simplejson.dumps(json) return HttpResponse(response, mimetype="application/json")
def _create_post_request(rf, directory, user, url='/', data={}): """Convenience function to create and setup fake POST requests.""" request = rf.post(url, data=data) request.user = user request.profile = get_profile(user) request.permissions = get_matching_permissions(request.profile, directory) return request
def user_joined_language(sender, instance, action, reverse, model, pk_set, **kwargs): if action == 'post_add' and not reverse: for project in instance.languages.filter(pk__in=pk_set).iterator(): message = 'User <a href="%s">%s</a> joined language <a href="%s">%s</a>' % ( instance.get_absolute_url(), get_profile(instance.user), project.get_absolute_url(), project.fullname) new_object(True, message, project.directory)
def view(request, path): #FIXME: why do we have leading and trailing slashes in pootle_path? pootle_path = '/%s' % path directory = get_object_or_404(Directory, pootle_path=pootle_path) request.permissions = get_matching_permissions(get_profile(request.user), directory) if not check_permission('view', request): raise PermissionDenied template_vars = {'path': path, 'directory': directory} # Find language and project defaults, passed to handle_form proj = None lang = None if not directory.is_language() and not directory.is_project(): translation_project = directory.translation_project lang = translation_project.language proj = translation_project.project else: if directory.is_language(): lang = directory.language proj = None if directory.is_project(): lang = None proj = directory.project if check_permission('administrate', request): # Thus, form is only set for the template if the user has # 'administrate' permission template_vars['form'] = handle_form(request, directory, proj, lang, template_vars) template_vars['title'] = directory_to_title(directory) else: template_vars['form'] = None if request.GET.get('all', False): template_vars['notices'] = Notice.objects.filter( directory__pootle_path__startswith=directory.pootle_path ).select_related('directory')[:30] else: template_vars['notices'] = Notice.objects.filter( directory=directory).select_related('directory')[:30] if not directory.is_language() and not directory.is_project(): request.translation_project = directory.translation_project template_vars['navitems'] = [ navbar_dict.make_directory_navbar_dict(request, directory) ] template_vars['translation_project'] = request.translation_project template_vars['language'] = request.translation_project.language template_vars['project'] = request.translation_project.project return render_to_response('notices.html', template_vars, context_instance=RequestContext(request))
def decorated_f(request, path_obj, *args, **kwargs): request.permissions = get_matching_permissions( get_profile(request.user), path_obj.directory) if check_permission(permission_code, request): return f(request, path_obj, *args, **kwargs) else: raise PermissionDenied( _("You do not have rights to administer %s.", path_obj.fullname))
def decorated_function(request, path_obj, *args, **kwargs): request.permissions = get_matching_permissions( get_profile(request.user), path_obj.directory) if check_permission(permission_code, request): return function(request, path_obj, *args, **kwargs) else: raise PermissionDenied( _("You do not have rights to administer %s.", path_obj.fullname))
def view(request, root_dir): request.permissions = get_matching_permissions(get_profile(request.user), root_dir) can_edit = request.user.is_superuser languages = getlanguages(request) languages_table_fields = ['language', 'progress', 'activity'] languages_table = { 'id': 'index-languages', 'proportional': False, 'fields': languages_table_fields, 'headings': get_table_headings(languages_table_fields), 'items': languages, } projects = getprojects(request) projects_table_fields = ['project', 'progress', 'activity'] projects_table = { 'id': 'index-projects', 'proportional': False, 'fields': projects_table_fields, 'headings': get_table_headings(projects_table_fields), 'items': projects, } siteconfig = load_site_config() ctx = { 'description': _(siteconfig.get('DESCRIPTION')), 'keywords': [ 'Pootle', 'translate', 'translation', 'localisation', 'localization', 'l10n', 'traduction', 'traduire', ], 'topstats': gentopstats_root(), 'permissions': request.permissions, 'can_edit': can_edit, 'languages_table': languages_table, 'projects_table': projects_table, 'resource_obj': request.resource_obj, 'moreprojects': (len(projects) > len(languages)) } if can_edit: from pootle_app.forms import GeneralSettingsForm ctx.update({ 'form': GeneralSettingsForm(siteconfig), 'form_action': reverse('pootle-admin-edit-settings'), }) return render_to_response('home/home.html', ctx, RequestContext(request))
def _handle_upload_form(request, translation_project): """Process the upload form in TP overview.""" from pootle_app.signals import post_file_upload upload_form_class = upload_form_factory(request) if request.method == 'POST' and 'file' in request.FILES: upload_form = upload_form_class(request.POST, request.FILES) if not upload_form.is_valid(): return upload_form else: django_file = upload_form.cleaned_data['file'] overwrite = upload_form.cleaned_data['overwrite'] upload_to = upload_form.cleaned_data['upload_to'] upload_to_dir = upload_form.cleaned_data['upload_to_dir'] # XXX Why do we scan here? translation_project.scan_files(vcs_sync=False) oldstats = translation_project.get_stats() # The URL relative to the URL of the translation project. Thus, if # directory.pootle_path == /af/pootle/foo/bar, then # relative_root_dir == foo/bar. if django_file.name.endswith('.zip'): archive = True target_directory = upload_to_dir or request.directory upload_archive(request, target_directory, django_file, overwrite) else: archive = False upload_file(request, request.directory, django_file, overwrite, store=upload_to) translation_project.scan_files(vcs_sync=False) newstats = translation_project.get_stats() # Create a submission. Doesn't fix stats but at least shows up in # last activity column. from django.utils import timezone s = Submission( creation_time=timezone.now(), translation_project=translation_project, submitter=get_profile(request.user), type=SubmissionTypes.UPLOAD, # The other fields are only relevant to unit-based changes. ) s.save() post_file_upload.send(sender=translation_project, user=request.user, oldstats=oldstats, newstats=newstats, archive=archive) # Always return a blank upload form unless the upload form is not valid. return upload_form_class()
def get_tp_metadata(request, pootle_path, uid=None): """ @return: An object in JSON notation that contains the metadata information about the current translation project: source/target language codes, the direction of the text and also a initial pager. Success status that indicates if the information has been succesfully retrieved or not is returned as well. """ if pootle_path[0] != '/': pootle_path = '/' + pootle_path profile = get_profile(request.user) json = {} try: store = Store.objects.select_related('translation_project', 'parent').get(pootle_path=pootle_path) if not check_profile_permission(profile, 'view', store.parent): json["success"] = False json["msg"] = _("You do not have rights to access translation mode.") else: units_qs = _filter_queryset(request.GET, store.units) unit_rows = profile.get_unit_rows() try: if uid is None: try: current_unit = units_qs[0] json["uid"] = units_qs[0].id except IndexError: current_unit = None else: current_unit = units_qs.get(id=uid, store__pootle_path=pootle_path) if current_unit is not None: current_index = _get_index_in_qs(units_qs, current_unit) preceding = units_qs[:current_index].count() page = preceding / unit_rows + 1 pager = paginate(request, units_qs, items=unit_rows, page=page) json["pager"] = _build_pager_dict(pager) tp = store.translation_project json["meta"] = {"source_lang": tp.project.source_language.code, "source_dir": tp.project.source_language.get_direction(), "target_lang": tp.language.code, "target_dir": tp.language.get_direction()} json["success"] = True except Unit.DoesNotExist: json["success"] = False json["msg"] = _("Unit %(uid)s does not exist on %(path)s." % {'uid': uid, 'path': pootle_path}) except Store.DoesNotExist: json["success"] = False json["msg"] = _("Store %(path)s does not exist." % {'path': pootle_path}) response = simplejson.dumps(json) return HttpResponse(response, mimetype="application/json")
def view(request, root_dir): request.permissions = get_matching_permissions(get_profile(request.user), root_dir) can_edit = request.user.is_superuser languages = getlanguages(request) languages_table_fields = ['language', 'progress', 'activity'] languages_table = { 'id': 'index-languages', 'proportional': False, 'fields': languages_table_fields, 'headings': get_table_headings(languages_table_fields), 'items': languages, } projects = getprojects(request) projects_table_fields = ['project', 'progress', 'activity'] projects_table = { 'id': 'index-projects', 'proportional': False, 'fields': projects_table_fields, 'headings': get_table_headings(projects_table_fields), 'items': projects, } templatevars = { 'description': _(settings.DESCRIPTION), 'keywords': [ 'Pootle', 'translate', 'translation', 'localisation', 'localization', 'l10n', 'traduction', 'traduire', ], 'topstats': gentopstats_root(), 'permissions': request.permissions, 'can_edit': can_edit, 'languages_table': languages_table, 'projects_table': projects_table, 'resource_obj': request.resource_obj, } templatevars['moreprojects'] = (len(projects) > len(languages)) if can_edit: from pootle_misc.siteconfig import load_site_config from pootle_app.forms import GeneralSettingsForm siteconfig = load_site_config() setting_form = GeneralSettingsForm(siteconfig) templatevars['form'] = setting_form return render_to_response('index/index.html', templatevars, RequestContext(request))
def get_units(request): """Gets source and target texts and its metadata. :return: A JSON-encoded object containing the source and target texts grouped by the store they belong to. When the ``pager`` GET parameter is present, pager information will be returned too. """ pootle_path = request.GET.get('path', None) if pootle_path is None: raise Http400(_('Arguments missing.')) page = None request.profile = get_profile(request.user) limit = request.profile.get_unit_rows() units_qs = Unit.objects.get_for_path(pootle_path, request.profile) step_queryset = get_step_query(request, units_qs) # Maybe we are trying to load directly a specific unit, so we have # to calculate its page number uid = request.GET.get('uid', None) if uid is not None: try: # XXX: Watch for performance, might want to drop into raw SQL # at some stage uid_list = list(step_queryset.values_list('id', flat=True)) preceding = uid_list.index(int(uid)) page = preceding / limit + 1 except ValueError: pass # uid wasn't a number or not present in the results pager = paginate(request, step_queryset, items=limit, page=page) unit_groups = [] units_by_path = groupby(pager.object_list, lambda x: x.store.pootle_path) for pootle_path, units in units_by_path: unit_groups.append(_path_units_with_meta(pootle_path, units)) response = { 'unit_groups': unit_groups, } if request.GET.get('pager', False): response['pager'] = { 'count': pager.paginator.count, 'number': pager.number, 'num_pages': pager.paginator.num_pages, 'per_page': pager.paginator.per_page, } return HttpResponse(jsonify(response), mimetype="application/json")
def view(request): request.permissions = get_matching_permissions(get_profile(request.user), Directory.objects.root) can_edit = request.user.is_superuser topstats = gentopstats_root() languages = getlanguages(request) templatevars = { 'description': _(settings.DESCRIPTION), 'keywords': [ 'Pootle', 'translate', 'translation', 'localisation', 'localization', 'l10n', 'traduction', 'traduire', ], 'languages': languages, 'projects': getprojects(request), 'topstats': topstats, 'translationlegend': { 'translated': _('Translations are complete'), 'fuzzy': _("Translations need to be checked " "(they are marked fuzzy)"), 'untranslated': _('Untranslated') }, 'permissions': request.permissions, 'can_edit': can_edit, } visible_langs = [l for l in languages if l['stats']['total']['words'] != 0] templatevars['moreprojects'] = (len(templatevars['projects']) > len(visible_langs)) if can_edit: from pootle_misc.siteconfig import load_site_config from pootle_app.forms import GeneralSettingsForm siteconfig = load_site_config() setting_form = GeneralSettingsForm(siteconfig) templatevars['form'] = setting_form return render_to_response('index/index.html', templatevars, RequestContext(request))
def view(request, path): pootle_path = '/%s' % path directory = get_object_or_404(Directory, pootle_path=pootle_path) request.permissions = get_matching_permissions(get_profile(request.user), directory) if not check_permission('view', request): raise PermissionDenied feedgen = NoticeFeed(pootle_path, request, directory).get_feed(path) response = HttpResponse(mimetype=feedgen.mime_type) feedgen.write(response, 'utf-8') return response
def _check_permissions(request, directory, permission_code): """Checks if the current user has enough permissions defined by `permission_code` in the current`directory`. """ request.profile = get_profile(request.user) request.permissions = get_matching_permissions(request.profile, directory) if not permission_code: return if not check_permission(permission_code, request): raise PermissionDenied(get_permission_message(permission_code))
def get_object(self, request, path): pootle_path = '/%s' % path directory = get_object_or_404(Directory, pootle_path=pootle_path) request.permissions = get_matching_permissions( get_profile(request.user), directory) if not check_permission('view', request): raise PermissionDenied self.directory = directory self.link = l(directory.pootle_path) self.recusrive = request.GET.get('all', False) return self.directory
def profile_edit(request): can_view = check_profile_permission(get_profile(request.user), "view", Directory.objects.root) if can_view: excluded = ('user', ) else: excluded = ('user', 'projects') return edit_profile(request, form_class=PootleProfileForm, extra_form_args={'exclude_fields': excluded})
def get_failing_checks(request, pootle_path): """ Gets a list of failing checks for the current query. @return: JSON string representing action status and depending on success, returns an error message or a list containing the the name and number of failing checks. """ pass if pootle_path[0] != '/': pootle_path = '/' + pootle_path profile = get_profile(request.user) json = {} try: store = Store.objects.select_related( 'translation_project', 'parent').get(pootle_path=pootle_path) if not check_profile_permission(profile, 'view', store.parent): json["success"] = False json["msg"] = _( "You do not have rights to access translation mode.") else: # Borrowed from pootle_app.views.language.item_dict.getcheckdetails checkopts = [] try: property_stats = store.getcompletestats() quick_stats = store.getquickstats() total = quick_stats['total'] keys = property_stats.keys() keys.sort() for checkname in keys: checkcount = property_stats[checkname] if total and checkcount: stats = ungettext('%(checkname)s (%(checks)d)', '%(checkname)s (%(checks)d)', checkcount, { "checks": checkcount, "checkname": checkname }) checkopt = {'name': checkname, 'text': stats} checkopts.append(checkopt) json["checks"] = checkopts json["success"] = True except IOError: json["success"] = False json["msg"] = _("Input/Output error.") except Store.DoesNotExist: json["success"] = False json["msg"] = _("Store %(path)s does not exist." % {'path': pootle_path}) response = simplejson.dumps(json) return HttpResponse(response, mimetype="application/json")
def project_language_index(request, project_code): """page listing all languages added to project""" project = get_object_or_404(Project, code=project_code) request.permissions = get_matching_permissions(get_profile(request.user), project.directory) if not check_permission('view', request): raise PermissionDenied can_edit = check_permission('administrate', request) translation_projects = project.translationproject_set.all() items = [make_language_item(request, translation_project) \ for translation_project in translation_projects.iterator()] items.sort(lambda x, y: locale.strcoll(x['title'], y['title'])) languagecount = len(translation_projects) project_stats = get_raw_stats(project) average = project_stats['translated']['percentage'] topstats = gentopstats_project(project) templatevars = { 'project': { 'code': project.code, 'name': project.fullname, 'description_html': project.description_html, 'summary': ungettext('%(languages)d language, %(average)d%% translated', '%(languages)d languages, %(average)d%% translated', languagecount, { "languages": languagecount, "average": average }), }, 'languages': items, 'topstats': topstats, 'statsheadings': get_stats_headings(), 'can_edit': can_edit, } if can_edit: from pootle_project.forms import DescriptionForm templatevars['form'] = DescriptionForm(instance=project) return render_to_response('project/project.html', templatevars, context_instance=RequestContext(request))