def add_widgets(result, fields, form, link, zebra): result.append('<tr class="%s">\n' % zebra) for i, field in enumerate(fields): result.append('<td class="%s">' % field) # Include a hidden element containing the form's id to the # first column. if i == 0: result.append(form['id'].as_hidden()) # `link` indicates whether we put the first field as a link or as # widget if field == linkfield and linkfield in form.initial and link: if callable(link): result.append(link(form.instance)) result.append(form[field].as_hidden()) else: link = l(link % form.initial[linkfield]) result.append("<a href='" + link + "'>" + form.initial[linkfield] + "</a>") result.append(form[field].as_hidden()) else: result.append(form[field].as_widget()) result.append('</td>\n') result.append('</tr>\n')
def project_admin(request, current_project): """Adding and deleting project languages.""" tp_form_class = tp_form_factory(current_project) queryset = TranslationProject.objects.filter(project=current_project) \ .order_by('pootle_path') model_args = { 'project': { 'code': current_project.code, 'name': current_project.fullname, } } link = lambda instance: '<a href="%s">%s</a>' % ( l(instance.pootle_path + 'admin_permissions.html'), instance.language, ) return util.edit(request, 'project/project_admin.html', TranslationProject, model_args, link, linkfield="language", queryset=queryset, can_delete=True, form=tp_form_class, formset=TranslationProjectFormSet, exclude=('description',))
def tp_admin_files(request, translation_project): queryset = translation_project.stores.all() if 'template_update' in request.POST: translation_project.update_from_templates() request.POST = {} if 'scan_files' in request.POST: translation_project.scan_files() for store in translation_project.stores.exclude(file='').iterator(): store.sync(update_translation=True) store.update(update_structure=True, update_translation=True, conservative=False) request.POST = {} model_args = { 'feed_path': translation_project.directory.pootle_path[1:], 'translation_project': translation_project, 'language': translation_project.language, 'project': translation_project.project, 'directory': translation_project.directory, } link = lambda instance: '<a href="%s/translate">%s</a>' % ( l(instance.pootle_path), instance.pootle_path[len(translation_project.pootle_path):] ) return util.edit(request, 'translation_project/tp_admin_files.html', Store, model_args, link, linkfield='pootle_path', queryset=queryset, formset=StoreFormset, can_delete=True, extra=0)
def download_zip(path_obj): if path_obj.is_dir: current_folder = path_obj.pootle_path else: current_folder = path_obj.parent.pootle_path # FIXME: ugly URL, django.core.urlresolvers.reverse() should work archive_name = "%sexport/zip" % current_folder return l(archive_name)
def link_func(_request, path_obj, **_kwargs): """Curried link function with self bound from instance method""" link = {'text': _(self.title), 'href': l(self._query_url(path_obj.pootle_path)), 'icon': getattr(self, 'icon', 'icon-vote-inactive')} if type(self).__doc__: link['tooltip'] = ' '.join(type(self).__doc__.split()) return link
def process_exception(self, request, exception): msg = force_unicode(exception) if isinstance(exception, Http404): if request.is_ajax(): return self._ajax_error(404, msg) elif isinstance(exception, PermissionDenied): if request.is_ajax(): return self._ajax_error(403, msg) templatevars = {} templatevars["permission_error"] = msg if not request.user.is_authenticated(): login_msg = _( 'You need to <a href="%(login_link)s">login</a> ' "to access this page.", {"login_link": "%s%s" % (l("/accounts/login/"), get_next(request))}, ) templatevars["login_message"] = login_msg return HttpResponseForbidden(render_to_string("403.html", templatevars, RequestContext(request))) else: # FIXME: implement better 500 tb = traceback.format_exc() print >>sys.stderr, tb if not settings.DEBUG: try: templatevars = {} templatevars["exception"] = msg if hasattr(exception, "filename"): msg = _( "Error accessing %(filename)s, Filesystem " "sent error: %(errormsg)s", {"filename": exception.filename, "errormsg": exception.strerror}, ) templatevars["fserror"] = msg if sentry_exception_handler is None: # Send email to admins with details about exception ip_type = request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS and "internal" or "EXTERNAL" subject = "Error (%s IP): %s" % (ip_type, request.path) try: request_repr = repr(request) except: request_repr = "Request repr() unavailable" message = "%s\n\n%s\n\n%s" % (unicode(exception.args[0]), tb, request_repr) mail_admins(subject, message, fail_silently=True) else: sentry_exception_handler(request=request) if request.is_ajax(): return self._ajax_error(500, msg) return HttpResponseServerError(render_to_string("500.html", templatevars, RequestContext(request))) except: # Let's not confuse things by throwing an exception here pass
def link_func(_request, path_obj, **_kwargs): """Curried link function with self bound from instance method""" link = {'text': _(self.title), 'icon': getattr(self, 'icon', 'icon-download')} export_path = self.get_download(path_obj) if export_path: abs_export_path = absolute_real_path(export_path) last_export = cache.get(self._cache_key(path_obj)) if last_export and (last_export == path_obj.get_mtime() and os.path.isfile(abs_export_path)): # valid and up-to-date cache file - link to that link['href'] = l("/export/" + export_path) if 'href' not in link: # no usable cache file, link to action query to generate it link['href'] = l(self._query_url(path_obj.pootle_path)) if type(self).__doc__: # return docstring with normalized whitespace as tooltip link['tooltip'] = ' '.join(type(self).__doc__.split()) return link
def download_source(request, path_obj, **kwargs): href = None if path_obj.name.startswith("pootle-terminology"): text = _("Download XLIFF") tooltip = _("Download file in XLIFF format") href = l('%s/export/xlf' % path_obj.pootle_path) elif path_obj.translation_project.project.is_monolingual(): text = _('Export') tooltip = _('Export translations') else: text = _('Download') tooltip = _('Download file') return { 'icon': 'icon-download', 'href': href or l('%s/download/' % path_obj.pootle_path), 'text': text, 'tooltip': tooltip, }
def render_search(context, form=None, action=None): translation_project = context["translation_project"] if form is None: is_terminology = translation_project.project.is_terminology form = make_search_form(terminology=is_terminology) if action is None: action = l("translate.html") template_vars = {"search_form": form, "search_action": action, "advanced_search_title": _("Advanced search")} return template_vars
def download_source(request, path_obj): href = None if path_obj.name.startswith("pootle-terminology"): text = _("Download XLIFF") tooltip = _("Download file in XLIFF format") href = l('%s/export/xlf' % path_obj.pootle_path) elif path_obj.translation_project.project.is_monolingual(): text = _('Export') tooltip = _('Export translations') else: text = _('Download') tooltip = _('Download file') return { 'icon': 'icon-download', 'href': href or l('%s/download/' % path_obj.pootle_path), 'text': text, 'tooltip': tooltip, }
def project_admin(request, project_code): """adding and deleting project languages""" current_project = Project.objects.get(code=project_code) request.permissions = get_matching_permissions( get_profile(request.user), current_project.directory) if not check_permission('administrate', request): raise PermissionDenied(_( "You do not have rights to administer this project.")) template_translation_project = current_project. \ get_template_translationproject() class TranslationProjectForm(forms.ModelForm): if template_translation_project is not None: update = forms.BooleanField(required=False, label=_( "Update from templates")) #FIXME: maybe we can detect if initialize is needed to avoid # displaying it when not relevant # initialize = forms.BooleanField( # required=False, label=_("Initialize")) project = forms.ModelChoiceField( queryset=Project.objects.filter(pk=current_project.pk), initial=current_project.pk, widget=forms.HiddenInput) language = LiberalModelChoiceField( label=_("Language"), queryset=Language.objects.exclude( translationproject__project=current_project)) class Meta: prefix = "existing_language" model = TranslationProject def process_extra_fields(self): if self.instance.pk is not None: if self.cleaned_data.get('initialize', None): self.instance.initialize() if self.cleaned_data.get('update', None) or not \ self.instance.stores.count(): self.instance.update_from_templates() queryset = TranslationProject.objects.filter( project=current_project).order_by('pootle_path') model_args = {} model_args['project'] = {'code': current_project.code, 'name': current_project.fullname} model_args['formid'] = "translation-projects" model_args['submitname'] = "changetransprojects" link = lambda instance: '<a href="/wikitrans%s">%s</a>' % ( l(instance.pootle_path + 'admin_permissions.html'), instance.language) return util.edit( request, 'project/project_admin.html', TranslationProject, model_args, link, linkfield="language", queryset=queryset, can_delete=True, form=TranslationProjectForm, formset=TranslationProjectFormSet)
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 _query_url(self, pootle_path): """Return relative URL for this action This is the URL that will be used to perform the action (via GET) - it is the pootle_path for the language, project, translationproject, or store, with a query component like "?ext_actions=Say+hello" where the value is the form-encoded title of the extension action instance. >>> ExtensionAction(category='X', title='Do it')._query_url("foo/bar") 'foo/bar?ext_actions=Do+it' """ return ''.join([l(pootle_path), '?', urlencode({EXTDIR: self.title})])
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 handle(self, **options): default_static_dir = os.path.join(settings.WORKING_DIR, 'static') custom_static_dirs = filter(lambda x: x != default_static_dir, settings.STATICFILES_DIRS) default_js_dir = os.path.join(default_static_dir, 'js') webpack_config_file = os.path.join(default_js_dir, 'webpack.config.js') webpack_bin = os.path.join(default_js_dir, 'node_modules/.bin/webpack') if os.name == 'nt': webpack_bin = '%s.cmd' % webpack_bin webpack_progress = ( '--progress' if options['progress'] or options['dev'] else '' ) webpack_colors = '--colors' if not options['no_color'] else '' webpack_args = [webpack_bin, '--config=%s' % webpack_config_file] if webpack_progress: webpack_args.append(webpack_progress) if webpack_colors: webpack_args.append(webpack_colors) if options['dev']: watch = '--watch' if options['watch'] else '' webpack_args.extend([watch, '--display-error-details']) else: os.environ['NODE_ENV'] = 'production' webpack_args.append("--bail") webpack_args.extend(options['extra']) static_base = l(settings.STATIC_URL) suffix = 'js/' if static_base.endswith('/') else '/js/' os.environ['WEBPACK_PUBLIC_PATH'] = static_base + suffix if custom_static_dirs: # XXX: review this for css # Append `js/` so that it's not necessary to reference it from the # `webpack.config.js` file custom_static_dirs = map(lambda x: os.path.join(x, 'js/'), custom_static_dirs) os.environ['WEBPACK_ROOT'] = ':'.join(custom_static_dirs) try: subprocess.call(webpack_args) except OSError: raise CommandError( 'webpack executable not found.\n' 'Make sure to install it by running ' '`cd %s && npm install`' % default_js_dir ) sys.exit(0)
def process_exception(self, request, exception): if isinstance(exception, Http404): pass elif isinstance(exception, PermissionDenied): templatevars = {} if len(exception.args) > 0: templatevars['permission_error'] = unicode(exception) if not request.user.is_authenticated(): login_msg = _( 'You need to <a href="%(login_link)s">login</a> ' \ 'to access this page.', {'login_link': l("/accounts/login/")}) templatevars["login_message"] = login_msg return HttpResponseForbidden( render_to_string( '403.html', templatevars, RequestContext(request))) else: #FIXME: implement better 500 trace = traceback.format_exc() print >> sys.stderr, trace if not settings.DEBUG: try: templatevars = {} if len(exception.args) > 0: templatevars['exception'] = unicode(exception.args[0]) if hasattr(exception, 'filename'): templatevars['fserror'] = _( 'Error accessing %(filename)s, Filesystem sent ' \ 'error: %(errormsg)s', {'filename': exception.filename, 'errormsg': exception.strerror}) # send email to admins with details about exception subject = 'Error (%s IP): %s' % ( (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), request.path) try: request_repr = repr(request) except: request_repr = "Request repr() unavailable" message = "%s\n\n%s\n\n%s" % ( unicode(exception.args[0]), trace, request_repr) mail_admins(subject, message, fail_silently=True) return HttpResponseServerError( render_to_string( '500.html', templatevars, RequestContext(request))) except: # let's not confuse things by throwing an exception here pass
def render_search(context, form=None, action=None): translation_project = context['translation_project'] if form is None: form = SearchForm() if action is None: action = l(translation_project.pootle_path + 'translate.html') template_vars = { 'search_form': form, 'search_action': action, 'advanced_search_title': _('Advanced search'), } return template_vars
def process_exception(self, request, exception): if isinstance(exception, Http404): pass elif isinstance(exception, PermissionDenied): templatevars = {} if len(exception.args) > 0: templatevars['permission_error'] = unicode(exception) if not request.user.is_authenticated(): login_msg = _( 'You need to <a href="%(login_link)s">login</a> to access this page.', {'login_link': l("/accounts/login/")}) templatevars["login_message"] = login_msg return HttpResponseForbidden( render_to_string('403.html', templatevars, RequestContext(request))) else: #FIXME: implement better 500 tb = traceback.format_exc() print >> sys.stderr, tb if not settings.DEBUG: try: templatevars = {} if len(exception.args) > 0: templatevars['exception'] = unicode(exception.args[0]) if hasattr(exception, 'filename'): templatevars['fserror'] = _( 'Error accessing %(filename)s, Filesystem sent error: %(errormsg)s', { 'filename': exception.filename, 'errormsg': exception.strerror }) # send email to admins with details about exception subject = 'Error (%s IP): %s' % ( (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), request.path) try: request_repr = repr(request) except: request_repr = "Request repr() unavailable" message = "%s\n\n%s\n\n%s" % (unicode( exception.args[0]), tb, request_repr) mail_admins(subject, message, fail_silently=True) return HttpResponseServerError( render_to_string('500.html', templatevars, RequestContext(request))) except: # let's not confuse things by throwing an exception here pass
def tp_admin_files(request, translation_project): queryset = translation_project.stores.all() if 'template_update' in request.POST: translation_project.update_from_templates() request.POST = {} if 'scan_files' in request.POST: translation_project.scan_files() for store in translation_project.stores.exclude(file='').iterator(): store.sync(update_translation=True) store.update(update_structure=True, update_translation=True, conservative=False) request.POST = {} model_args = { 'title': _("Files"), 'submitname': "changestores", 'formid': "stores", 'navitems': [ navbar_dict.make_directory_navbar_dict( request, translation_project.directory) ], 'feed_path': translation_project.directory.pootle_path[1:], 'translation_project': translation_project, 'language': translation_project.language, 'project': translation_project.project, 'directory': translation_project.directory, } link = lambda instance: '<a href="%s/translate">%s</a>' % (l( instance.pootle_path), instance.pootle_path[len(translation_project. pootle_path):]) return util.edit(request, 'translation_project/tp_admin_files.html', Store, model_args, link, linkfield='pootle_path', queryset=queryset, formset=StoreFormset, can_delete=True, extra=0)
def handle(self, **options): default_static_dir = os.path.join(settings.WORKING_DIR, 'static') custom_static_dirs = filter(lambda x: x != default_static_dir, settings.STATICFILES_DIRS) default_js_dir = os.path.join(default_static_dir, 'js') webpack_config_file = os.path.join(default_js_dir, 'webpack.config.js') webpack_bin = os.path.join(default_js_dir, 'node_modules/.bin/webpack') if os.name == 'nt': webpack_bin = '%s.cmd' % webpack_bin webpack_progress = ('--progress' if options['progress'] or options['dev'] else '') webpack_colors = '--colors' if not options['no_color'] else '' webpack_args = [webpack_bin, '--config=%s' % webpack_config_file] if webpack_progress: webpack_args.append(webpack_progress) if webpack_colors: webpack_args.append(webpack_colors) if options['dev']: watch = '--watch' if options['watch'] else '' webpack_args.extend([watch, '--display-error-details']) else: os.environ['NODE_ENV'] = 'production' webpack_args.append("--bail") webpack_args.extend(options['extra']) static_base = l(settings.STATIC_URL) suffix = 'js/' if static_base.endswith('/') else '/js/' os.environ['WEBPACK_PUBLIC_PATH'] = static_base + suffix if custom_static_dirs: # XXX: review this for css # Append `js/` so that it's not necessary to reference it from the # `webpack.config.js` file custom_static_dirs = map(lambda x: os.path.join(x, 'js/'), custom_static_dirs) os.environ['WEBPACK_ROOT'] = ':'.join(custom_static_dirs) try: subprocess.call(webpack_args) except OSError: raise CommandError('webpack executable not found.\n' 'Make sure to install it by running ' '`cd %s && npm install`' % default_js_dir) sys.exit(0)
def render_search(context, form=None, action=None): translation_project = context['translation_project'] if form is None: is_terminology = translation_project.project.is_terminology form = make_search_form(terminology=is_terminology) if action is None: action = l('translate.html') template_vars = { 'search_form': form, 'search_action': action, 'advanced_search_title': _('Advanced search'), } return template_vars
def translate(path_obj, state=None, check=None): # In Pootle, URLs ending in translate.html are used when the user # translates all files in a directory (for example, if the user is # going through all fuzzy translations in a directory). path = path_obj.pootle_path if path.endswith('/'): path += 'translate.html' else: path += '/translate/' if state: path += '#filter=%s' % state elif check: path += '#filter=checks,%s' % check return l(path)
def render_search(context, form=None, action=None): if form is None: request = context['request'] translation_project = context['translation_project'] is_terminology = translation_project.project.is_terminology form = make_search_form(request=request, terminology=is_terminology) if action is None: action = l('translate.html') template_vars = { 'search_form': form, 'search_action': action, } return template_vars
def translate(path_obj, state=None, check=None, user=None): # In Pootle, URLs ending in translate.html are used when the user # translates all files in a directory (for example, if the user is # going through all fuzzy translations in a directory). path = path_obj.pootle_path if path.endswith('/'): path += 'translate.html' else: path += '/translate/' if state: path += '#filter=%s' % state if user: path += '&user=%s' % user elif check: path += '#filter=checks&checks=%s' % check return l(path)
def translate(path_obj, state=None, check=None, suggestions=False): # In Pootle, URLs ending in translate.html are used when the user # translates all files in a directory (for example, if the user is # going through all fuzzy translations in a directory). path = path_obj.pootle_path if path.endswith("/"): path += "translate.html" else: path += "/translate/" if state: path += "#filter=%s" % state elif check: path += "#filter=checks,%s" % check elif suggestions: path += "#filter=suggestions" return l(path)
def get_absolute_url(self): return l(self.pootle_path)
def export(pootle_path, format): return l('%s/export/%s' % (pootle_path, format))
def get_absolute_url(self): return l(self.pootle_path + '/translate/')
def commit_all(path_obj): return l(path_obj.pootle_path + 'commit_all')
def commit(path_obj): return l(path_obj.pootle_path + '/commit')
def open_translation_project(language_code, project_code): return l('/%s/%s/' % (language_code, project_code))
def get_translate_incomplete_url(self): return l(self.pootle_path) + 'translate.html#filter=incomplete'
def project_admin(request, current_project): """adding and deleting project languages""" template_translation_project = current_project \ .get_template_translationproject() class TranslationProjectForm(forms.ModelForm): if template_translation_project is not None: update = forms.BooleanField(required=False, label=_("Update against templates")) #FIXME: maybe we can detect if initialize is needed to avoid # displaying it when not relevant #initialize = forms.BooleanField(required=False, label=_("Initialize")) project = forms.ModelChoiceField( queryset=Project.objects.filter(pk=current_project.pk), initial=current_project.pk, widget=forms.HiddenInput ) language = LiberalModelChoiceField( label=_("Language"), queryset=Language.objects.exclude( translationproject__project=current_project), widget=forms.Select(attrs={ 'class': 'js-select2 select2-language', }), ) class Meta: prefix = "existing_language" model = TranslationProject def process_extra_fields(self): if self.instance.pk is not None: if self.cleaned_data.get('initialize', None): self.instance.initialize() if (self.cleaned_data.get('update', None) or not self.instance.stores.count()): self.instance.update_against_templates() queryset = TranslationProject.objects.filter( project=current_project).order_by('pootle_path') model_args = { 'project': { 'code': current_project.code, 'name': current_project.fullname, } } link = lambda instance: '<a href="%s">%s</a>' % ( l(instance.pootle_path + 'admin_permissions.html'), instance.language, ) return util.edit(request, 'project/project_admin.html', TranslationProject, model_args, link, linkfield="language", queryset=queryset, can_delete=True, form=TranslationProjectForm, formset=TranslationProjectFormSet, exclude=('description',))
def get_absolute_url(self): return l(self.directory.pootle_path + 'notices/%d' % self.id)
def process_exception(self, request, exception): msg = force_unicode(exception) if isinstance(exception, Http404): if request.is_ajax(): return self._ajax_error(404, msg) elif isinstance(exception, PermissionDenied): if request.is_ajax(): return self._ajax_error(403, msg) templatevars = {} templatevars['permission_error'] = msg if not request.user.is_authenticated(): login_msg = _('You need to <a href="%(login_link)s">login</a> ' 'to access this page.', {'login_link': "%s%s" % \ (l("/accounts/login/"), get_next(request))}) templatevars["login_message"] = login_msg return HttpResponseForbidden( render_to_string('403.html', templatevars, RequestContext(request))) elif (exception.__class__.__name__ in ('OperationalError', 'ProgrammingError', 'DatabaseError')): # HACKISH: Since exceptions thrown by different databases do # not share the same class heirarchy (DBAPI2 sucks) we have to # check the class name instead. Since python uses duck typing # I will call this # poking-the-duck-until-it-quacks-like-a-duck-test return HttpResponseServerError( render_to_string('db_error.html', {'exception': msg}, RequestContext(request))) else: #FIXME: implement better 500 tb = traceback.format_exc() print >> sys.stderr, tb if not settings.DEBUG: try: templatevars = {} templatevars['exception'] = msg if hasattr(exception, 'filename'): msg = _( 'Error accessing %(filename)s, Filesystem ' 'sent error: %(errormsg)s', { 'filename': exception.filename, 'errormsg': exception.strerror }) templatevars['fserror'] = msg if sentry_exception_handler is None: # Send email to admins with details about exception ip_type = (request.META.get('REMOTE_ADDR') in \ settings.INTERNAL_IPS and 'internal' or 'EXTERNAL') subject = 'Error (%s IP): %s' % (ip_type, request.path) try: request_repr = repr(request) except: request_repr = "Request repr() unavailable" message = "%s\n\n%s\n\n%s" % (unicode( exception.args[0]), tb, request_repr) mail_admins(subject, message, fail_silently=True) else: sentry_exception_handler(request=request) if request.is_ajax(): return self._ajax_error(500, msg) return HttpResponseServerError( render_to_string('500.html', templatevars, RequestContext(request))) except: # Let's not confuse things by throwing an exception here pass
def __init__(self, slug, request, directory): self.link = l(directory.pootle_path) self.directory = directory self.recusrive = request.GET.get('all', False) super(NoticeFeed, self).__init__(slug, request)
def export(pootle_path, format): return l('/export-file/%s%s' % (format, pootle_path))
def project_admin(request, project_code): """adding and deleting project languages""" current_project = Project.objects.get(code=project_code) request.permissions = get_matching_permissions(get_profile(request.user), current_project.directory) if not check_permission('administrate', request): raise PermissionDenied( _("You do not have rights to administer this project.")) template_translation_project = current_project.get_template_translationproject( ) class TranslationProjectForm(forms.ModelForm): if template_translation_project is not None: update = forms.BooleanField(required=False, label=_("Update from templates")) #FIXME: maybe we can detect if initialize is needed to avoid # displaying it when not relevant #initialize = forms.BooleanField(required=False, label=_("Initialize")) project = forms.ModelChoiceField( queryset=Project.objects.filter(pk=current_project.pk), initial=current_project.pk, widget=forms.HiddenInput) language = LiberalModelChoiceField( label=_("Language"), queryset=Language.objects.exclude( translationproject__project=current_project)) class Meta: prefix = "existing_language" model = TranslationProject def process_extra_fields(self): if self.instance.pk is not None: if self.cleaned_data.get('initialize', None): self.instance.initialize() if self.cleaned_data.get( 'update', None) or not self.instance.stores.count(): self.instance.update_from_templates() queryset = TranslationProject.objects.filter( project=current_project).order_by('pootle_path') model_args = {} model_args['project'] = { 'code': current_project.code, 'name': current_project.fullname } model_args['formid'] = "translation-projects" model_args['submitname'] = "changetransprojects" link = lambda instance: '<a href="%s">%s</a>' % (l( instance.pootle_path + 'admin_permissions.html'), instance.language) return util.edit(request, 'project/project_admin.html', TranslationProject, model_args, link, linkfield="language", queryset=queryset, can_delete=True, form=TranslationProjectForm, formset=TranslationProjectFormSet)
def update(path_obj): return l(path_obj.pootle_path + '/update')
def update_all(path_obj): return l(path_obj.pootle_path + 'update_all')
def open_language(code): return l('/%s/' % code)
def project_admin(request, current_project): """adding and deleting project languages""" template_translation_project = current_project \ .get_template_translationproject() class TranslationProjectForm(forms.ModelForm): if template_translation_project is not None: update = forms.BooleanField(required=False, label=_("Update against templates")) #FIXME: maybe we can detect if initialize is needed to avoid # displaying it when not relevant #initialize = forms.BooleanField(required=False, label=_("Initialize")) project = forms.ModelChoiceField( queryset=Project.objects.filter(pk=current_project.pk), initial=current_project.pk, widget=forms.HiddenInput) language = LiberalModelChoiceField( label=_("Language"), queryset=Language.objects.exclude( translationproject__project=current_project), widget=forms.Select(attrs={ 'class': 'js-select2 select2-language', }), ) class Meta: prefix = "existing_language" model = TranslationProject def process_extra_fields(self): if self.instance.pk is not None: if self.cleaned_data.get('initialize', None): self.instance.initialize() if (self.cleaned_data.get('update', None) or not self.instance.stores.count()): self.instance.update_against_templates() queryset = TranslationProject.objects.filter( project=current_project).order_by('pootle_path') model_args = { 'project': { 'code': current_project.code, 'name': current_project.fullname, } } link = lambda instance: '<a href="%s">%s</a>' % ( l(instance.pootle_path + 'admin_permissions.html'), instance.language, ) return util.edit(request, 'project/project_admin.html', TranslationProject, model_args, link, linkfield="language", queryset=queryset, can_delete=True, form=TranslationProjectForm, formset=TranslationProjectFormSet, exclude=('description', ))
def get_absolute_url(self): return l('/accounts/%s/' % self.user.username)
def process_exception(self, request, exception): msg = force_unicode(exception) if isinstance(exception, Http404): if request.is_ajax(): return self._ajax_error(404, msg) elif isinstance(exception, Http400): if request.is_ajax(): return self._ajax_error(400, msg) elif isinstance(exception, PermissionDenied): if request.is_ajax(): return self._ajax_error(403, msg) templatevars = { 'permission_error': msg, } if not request.user.is_authenticated(): msg_args = { 'login_link': "%s%s" % (l("/accounts/login/"), get_next(request)), } login_msg = _('You need to <a href="%(login_link)s">login</a> ' 'to access this page.', msg_args) templatevars["login_message"] = login_msg return HttpResponseForbidden( render_to_string('403.html', templatevars, RequestContext(request)) ) elif (exception.__class__.__name__ in ('OperationalError', 'ProgrammingError', 'DatabaseError')): # HACKISH: Since exceptions thrown by different databases do # not share the same class heirarchy (DBAPI2 sucks) we have to # check the class name instead. Since python uses duck typing # I will call this # poking-the-duck-until-it-quacks-like-a-duck-test return HttpResponseServerError( render_to_string('db_error.html', {'exception': msg}, RequestContext(request)) ) else: #FIXME: implement better 500 tb = traceback.format_exc() print >> sys.stderr, tb if not settings.DEBUG: try: templatevars = { 'exception': msg, } if hasattr(exception, 'filename'): msg_args = { 'filename': exception.filename, 'errormsg': exception.strerror, } msg = _('Error accessing %(filename)s, Filesystem ' 'sent error: %(errormsg)s', msg_args) templatevars['fserror'] = msg if sentry_exception_handler is None: # Send email to admins with details about exception ip_type = (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL') msg_args = { 'ip_type': ip_type, 'path': request.path, } subject = 'Error (%(ip_type)s IP): %(path)s' % msg_args try: request_repr = repr(request) except: request_repr = "Request repr() unavailable" msg_args = (unicode(exception.args[0]), tb, request_repr) message = "%s\n\n%s\n\n%s" % msg_args mail_admins(subject, message, fail_silently=True) else: sentry_exception_handler(request=request) if request.is_ajax(): return self._ajax_error(500, msg) return HttpResponseServerError( render_to_string('500.html', templatevars, RequestContext(request))) except: # Let's not confuse things by throwing an exception here pass