Пример #1
0
def login_user(request):
    state = "Login Below...."
    username = password = ''
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                state = None
                #state = "You're successfully logged in!"
            else:
                state = "Your account is not active, please contact the site admin."
        else:
            state = "Your username and/or password were incorrect."
#    print "========="
#    print state
    
    
    print "=" * 50
    print request.LANGUAGE_CODE
    print translation.get_language_from_request(request)        
    #translation.activate('de')
    print translation.get_language()

    print "=" * 50
    
    
    if state:
        return render_to_response('auth.html', locals(), context_instance=RequestContext(request))
    return render_to_response('chat.html', locals(), context_instance=RequestContext(request))
Пример #2
0
 def process_request(self, request):
     
     from django.utils import translation
             
     path_tuple = request.path_info.split("/")
     
     if len(path_tuple) > 1:
         
         if path_tuple[1] in settings.NOT_LANG_URLS:
             return
     
         if check_for_language(path_tuple[1]):
             
             lang = path_tuple[1]
             
             if hasattr(request, 'session'):
                 request.session['django_language'] = lang
             
             request.COOKIES['django_language'] = lang
         
             set_default_language(lang)
             request.path_info = "/" + "/".join(path_tuple[2:])                
             return
     
     if hasattr(request, "session") and "django_language" in request.session:
         lang = request.session["django_language"]
     elif hasattr(request, "COOKIE") and "django_language" in request.COOKIE:
         lang = request.COOKIE["django_language"]
     elif check_for_language(get_language_from_request(request)):
         set_default_language(get_language_from_request(request))
         lang = get_language_from_request(request)
     else:
         lang = settings.LANGUAGES[settings.DEFAULT_LANGUAGE][0]
         
     return HttpResponseRedirect('/%s%s' % (lang, request.path_info))
Пример #3
0
 def get_language_from_request (self,request):
     supported = dict(settings.LANGUAGES)
     lang = settings.LANGUAGE_CODE[:2]
     langs = "|".join(map(lambda l: l[0], settings.LANGUAGES))
     check = re.match(r"^/(%s)/.*" % langs, request.path_info)
     changed = False
     if check is not None:
         request.path = request.path[3:]
         request.path_info = request.path_info[3:]
         t = check.group(1)
         if t in supported:
             lang = t
             if hasattr(request, "session"):
                 request.session["django_language"] = lang
             else:
                 request.set_cookie("django_language", lang)
             changed = True
     else:
         lang = translation.get_language_from_request(request)
     if not changed:
         if hasattr(request, "session"):
             lang = request.session.get("django_language", None)
             if lang in supported and lang is not None:
                 return lang
         elif "django_language" in request.COOKIES.keys():
             lang = request.COOKIES.get("django_language", None)
             if lang in supported and lang is not None:
                 return lang
         if not lang:
             lang = translation.get_language_from_request(request) 
     return lang
Пример #4
0
 def get_language_from_request(self,request):
     changed = False
     prefix = has_lang_prefix(request.path_info)
     pages_root = urllib.unquote(reverse("home"))
     if prefix:
         request.path = request.path.split("/")
         del request.path[pages_root.count('/')]
         request.path = "/".join(request.path)
         request.path_info = "/" + "/".join(request.path_info.split("/")[2:])
         t = prefix
         if t in SUPPORTED:
             lang = t
             if hasattr(request, "session"):
                 request.session["django_language"] = lang
             changed = True
     else:
         lang = translation.get_language_from_request(request)
     if not changed:
         if hasattr(request, "session"):
             lang = request.session.get("django_language", None)
             if lang in SUPPORTED and lang is not None:
                 return lang
         elif "django_language" in request.COOKIES.keys():
             lang = request.COOKIES.get("django_language", None)
             if lang in SUPPORTED and lang is not None:
                 return lang
         if not lang:
             lang = translation.get_language_from_request(request)
     lang = get_default_language(lang)
     return lang
Пример #5
0
 def get_language_from_request (self,request):
     changed = False
     prefix = has_lang_prefix(request.path_info)
     if prefix:
         request.path = "/" + "/".join(request.path.split("/")[2:])
         request.path_info = "/" + "/".join(request.path_info.split("/")[2:])
         t = prefix
         if t in self.SUPPORTED:
             lang = t
             if hasattr(request, "session"):
                 request.session["django_language"] = lang
             changed = True
     else:
         lang = translation.get_language_from_request(request)
     if not changed:
         if hasattr(request, "session"):
             lang = request.session.get("django_language", None)
             if lang in self.SUPPORTED and lang is not None:
                 return lang
         elif "django_language" in request.COOKIES.keys():
             lang = request.COOKIES.get("django_language", None)
             if lang in self.SUPPORTED and lang is not None:
                 return lang
         if not lang:
             lang = translation.get_language_from_request(request)
     lang = 'tr'#get_default_language(lang)
     return lang
Пример #6
0
 def get_language_from_request(self,request):
     changed = False
     prefix = has_lang_prefix(request.path_info)
     lang = None
     if prefix:
         request.path = "/" + "/".join((request.META.get('SCRIPT_URL', "") or request.path).split("/")[2:])
         request.path_info = "/" + "/".join((request.META.get('SCRIPT_URL', "") or request.path_info).split("/")[2:])
         t = prefix
         if t in SUPPORTED:
             lang = t
             if hasattr(request, "session"):
                 request.session["django_language"] = lang
             changed = True
     else:
         lang = translation.get_language_from_request(request)
     if not changed:
         if hasattr(request, "session"):
             lang = request.session.get("django_language", None)
             if lang in SUPPORTED and lang is not None:
                 return lang
         elif "django_language" in request.COOKIES.keys():
             lang = request.COOKIES.get("django_language", None)
             if lang in SUPPORTED and lang is not None:
                 return lang
         if not lang:
             lang = translation.get_language_from_request(request)
     if not lang:
         lang = settings.LANGUAGE_CODE
     return lang
Пример #7
0
 def get_language_from_request(self, request):
     
     changed = False
     prefix = self.has_lang_prefix(request.path_info)
     if prefix:
         request.path = "/" + "/".join(request.path.split("/")[2:])
         request.path_info = request.path
         t = prefix
         if t in self.get_supported_languages():
             lang = t
             if hasattr(request, "session") and request.session.get("django_language", None) != lang:
                 request.session["django_language"] = lang
             changed = True
     else:
         lang = translation.get_language_from_request(request)
     
     if not changed:
         if hasattr(request, "session"):
             lang = request.session.get("django_language", None)
             if lang in self.get_supported_languages() and lang is not None:
                 return lang
         
         elif "django_language" in request.COOKIES.keys():
             lang = request.COOKIES.get("django_language", None)
             if lang in self.get_supported_languages() and lang is not None:
                 return lang
     
         if not lang:
             lang = translation.get_language_from_request(request)
     
     return lang
Пример #8
0
 def _get_user_lang(self, request, profile):
     try:
         lang = profile.language    
     except:
         lang = translation.get_language_from_request(request)
     else:
         supported = dict(settings.LANGUAGES)
         if lang not in supported:
             lang = translation.get_language_from_request(request)
     return lang
 def process_request(self, request):
     if request.session.get('django_language'):
         language = translation.get_language_from_request(request)
     elif request.COOKIES.get('django_language'):
         language = translation.get_language_from_request(request)
     else:
         language = 'nl'
     #language = translation.get_language_from_request(request)
     translation.activate(language)
     request.LANGUAGE_CODE = translation.get_language()
     
Пример #10
0
 def form_valid(self, form):
     lang = translation.get_language_from_request(self.request)
     # Update translation in editing user's language
     for an in form.instance.names.filter(language=lang):
         an.altername = form.instance.name
         an.save()
     return super(UpdateLocationView, self).form_valid(form)
Пример #11
0
 def form_valid(self, form):
     # Create user instance with fixed username
     form.instance.username = create_username(
         form.instance.first_name,
         form.instance.last_name
     )
     form.instance.is_active = False
     form.instance.set_password(form.cleaned_data['password1'])
     form.instance.save()
     # Create token for mobile API
     Token.objects.create(user=form.instance)
     # Create registration link and save along with request params
     salt = hashlib.md5()
     salt.update(settings.SECRET_KEY + str(datetime.datetime.now().time))
     register_demand = RegisterDemand.objects.create(
         activation_link = salt.hexdigest(),
         ip_address = ip.get_ip(self.request),
         user = form.instance,
         email = form.instance.email,
         lang = translation.get_language_from_request(self.request)
     )
     # Create full link to activation page for new user
     site_url = self.request.build_absolute_uri('/user/activate/')
     link = site_url + str(register_demand.activation_link)
     # Send email in user's own language if possible
     email = emails.ActivationLink()
     email_context = {'link': link}
     if translation.check_for_language(register_demand.lang):
         email_context.update({'lang': register_demand.lang})
     email.send(register_demand.email, email_context)
     return render(self.request, 'userspace/register-success.html',
                                     {'title': _("Message send"),})
Пример #12
0
 def get_context_data(self, **kwargs):
     context = super(NavigationMixin, self).get_context_data(**kwargs)
     language = get_language_from_request(self.request, check_path=True)
     events_by_year = build_events_by_year(
         events=(
             Event.objects.namespace(self.namespace)
                          .future()
                          .active_translations(language)
                          .language(language)
         )
     )
     context['events_by_year'] = events_by_year
     archived_events_by_year = build_events_by_year(
         events=(
             Event.objects.namespace(self.namespace)
                          .archive()
                          .active_translations(language)
                          .language(language)
         ),
         is_archive_view=True,
     )
     context['archived_events_by_year'] = archived_events_by_year
     context['event_year'] = self.kwargs.get('year')
     context['event_month'] = self.kwargs.get('month')
     context['event_day'] = self.kwargs.get('day')
     return context
Пример #13
0
    def render(self, context, instance, placeholder):
        self.render_template = (
            'aldryn_events/plugins/list/%s/list.html' % instance.style
        )
        language = (
            instance.language or
            get_language_from_request(context['request'], check_path=True)
        )
        context['instance'] = instance

        namespace = instance.app_config_id and instance.app_config.namespace
        # check if we can reverse list view for configured namespace
        # if no prepare a message to admin users.
        if not is_valid_namespace(namespace):
            # add message, should be properly handled in template
            context['plugin_configuration_error'] = NO_APPHOOK_ERROR_MESSAGE
            return context
        # With Django 1.5 and because a bug in SortedManyToManyField
        # we can not use instance.events or we get a error like:
        # DatabaseError:
        #   no such column: aldryn_events_eventlistplugin_events.sort_value
        events = (Event.objects.namespace(namespace)
                               .active_translations(language)
                               .language(language)
                               .filter(eventlistplugin__pk=instance.pk))

        context['events'] = events
        return context
Пример #14
0
 def __init__(self, request=None):
     self.user = AnonymousUser()
     self.timezone = settings.TIME_ZONE
     if request is not None:
         self.language = get_language_from_request(request)
     else:
         self.language = settings.LANGUAGE_CODE
Пример #15
0
    def get_nodes(self, request):
        nodes = []
        language = get_language_from_request(request, check_path=True)

        # NOTE: It is important that we only get objects that have an active
        # translation, otherwise, object.get_absolute_url() may return
        # NoReverseMatch exceptions that we will have to catch, if we want to
        # prevent errors from appearing on-screen.
        things = (Thing.objects.published()
                               .language(language)
                               .active_translations(language))

        if hasattr(self, 'instance') and self.instance:  # pragma: no cover
            # If self has a property `instance`, then we're using django CMS
            # 3.0.12 or later, which supports using CMSAttachMenus on multiple,
            # apphook'ed pages, each with their own apphook configuration. So,
            # here we modify the queryset to reflect this.
            app = apphook_pool.get_apphook(self.instance.application_urls)
            if app:
                things = things.namespace(self.instance.application_namespace)

        for thing in things:
            # This try/except seems like overkill here, but if this fails for
            # any reason, this **and any further menus, even from other apps**
            # may not get loaded, so we're extra careful.
            try:
                url = thing.get_absolute_url(language=language)
                node = NavigationNode(thing.name, url, thing.pk)
                nodes.append(node)
            except NoReverseMatch:  # pragma: no cover
                pass

        return nodes
Пример #16
0
 def __init__(self, request=None):
     self.user = AnonymousUser()
     self.timezone = settings.TIME_ZONE
     if request is None:
         self.language = settings.LANGUAGE_CODE
     else:
         self.language = translation.get_language_from_request(request, check_path=True)
Пример #17
0
    def render(self, context, instance, placeholder):
        # translated filter the events, language set current language
        language = get_language_from_request(context['request'],
                                             check_path=True)
        namespace = instance.app_config_id and instance.app_config.namespace
        self.render_template = (
            'aldryn_events/plugins/upcoming/%s/upcoming.html' % instance.style
        )
        context['instance'] = instance
        # check if we can reverse list view for configured namespace
        # if no prepare a message to admin users.
        if not is_valid_namespace(namespace):
            # add message, should be properly handled in template
            context['plugin_configuration_error'] = NO_APPHOOK_ERROR_MESSAGE
            return context

        events = (Event.objects.namespace(namespace)
                               .active_translations(language)
                               .language(language))

        if instance.past_events:
            events = events.past(count=instance.latest_entries)
        else:
            events = events.upcoming(count=instance.latest_entries)

        context['events'] = events
        return context
Пример #18
0
 def get_form_kwargs(self):
     kwargs = super(EventDetailView, self).get_form_kwargs()
     kwargs['event'] = self.event
     kwargs['language_code'] = (
         get_language_from_request(self.request, check_path=True)
     )
     return kwargs
Пример #19
0
def preferences(request):
  if request.method == 'POST':
    form = PreferencesForm(request.POST)
    if form.is_valid():
      try:
        newdata = form.cleaned_data
        request.user.language = newdata['language']
        request.user.theme = newdata['theme']
        request.user.pagesize = newdata['pagesize']
        request.user.save()
        # Switch to the new theme and language immediately
        request.theme = newdata['theme']
        if newdata['language'] == 'auto':
          newdata['language'] = translation.get_language_from_request(request)
        if translation.get_language() != newdata['language']:
          translation.activate(newdata['language'])
          request.LANGUAGE_CODE = translation.get_language()
        messages.add_message(request, messages.INFO, force_unicode(_('Successfully updated preferences')))
      except Exception as e:
        logger.error("Failure updating preferences: %s" % e)
        messages.add_message(request, messages.ERROR, force_unicode(_('Failure updating preferences')))
  else:
    pref = request.user
    form = PreferencesForm({
      'language': pref.language,
      'theme': pref.theme,
      'pagesize': pref.pagesize,
      })
  return render_to_response('common/preferences.html', {
     'title': _('Edit my preferences'),
     'form': form,
     },
     context_instance=RequestContext(request))
Пример #20
0
    def get_queryset(self):
        qs = (super(EventListView, self).get_queryset()
                                        .namespace(self.namespace))

        if not self.request.GET.get('all_languages', False):
            language = get_language_from_request(self.request, check_path=True)
            qs = qs.active_translations(language).language(language)

        year = self.kwargs.get('year')
        month = self.kwargs.get('month')
        day = self.kwargs.get('day')

        self.archive_qs = []

        if year or month or day:
            tz = get_current_timezone()
            if year and month and day:
                year, month, day = map(int, [year, month, day])
                _date = date(year, month, day)

                qs = qs.filter(
                    Q(start_date=_date, end_date__isnull=True) |
                    Q(start_date__lte=_date, end_date__gte=_date)
                ).published()
            elif year and month:
                year, month = map(int, [year, month])
                date_start = date(year, month, 1)
                date_end = date_start + relativedelta(months=1, days=-1)

                qs = qs.filter(
                    Q(start_date__range=(date_start, date_end),
                      end_date__isnull=True) |
                    Q(start_date__range=(date_start, date_end),
                      end_date__lte=date_end) |
                    Q(start_date__lt=date_start,
                      end_date__range=(date_start, date_end)) |
                    Q(start_date__lt=date_start,
                      end_date__gte=date_end)
                ).published()
            else:
                year = int(year)
                date_start = date(year, 1, 1)
                date_end = date_start + relativedelta(years=1, days=-1)

                qs = qs.filter(
                    Q(start_date__range=(date_start, date_end),
                      end_date__isnull=True) |
                    Q(start_date__range=(date_start, date_end),
                      end_date__lte=date_end) |
                    Q(start_date__lt=date_start,
                      end_date__range=(date_start, date_end))
                ).published()
        else:
            if self.archive:
                qs = qs.archive()
            else:
                self.archive_qs = qs.archive().order_by(*ORDERING_FIELDS)
                qs = qs.future()

        return qs.order_by(*ORDERING_FIELDS).distinct()
Пример #21
0
    def get_published_pagelist(self, request, *args, **kwargs):
        """
        This view is used by the SearchLinkField as the user types to feed the autocomplete drop-down.
        """
        if not request.is_ajax():
            return HttpResponseForbidden()

        query_term = request.GET.get('term','').strip('/')
        language = get_language_from_request(request)
        matching_published_pages = Page.objects.published().public().filter(
            Q(title_set__title__icontains=query_term, title_set__language=language)
            | Q(title_set__path__icontains=query_term, title_set__language=language)
            | Q(title_set__menu_title__icontains=query_term, title_set__language=language)
            | Q(title_set__page_title__icontains=query_term, title_set__language=language)
        ).distinct().order_by('title_set__title').iterator()

        data = {'results': []}
        for page in matching_published_pages:
            title = page.get_title(language=language)
            path = page.get_absolute_url(language=language)
            data['results'].append({
                'id': page.pk,
                'text': format_page_link(title, path),
            })
            if len(data['results']) > 15:
                break
        return JsonResponse(data)
Пример #22
0
    def process_request(self, request):
        if request.user.is_authenticated():
            try:
                # Here we try to load profile, but can get error
                # if user created during syncdb but profile model
                # under south control. (Like pybb.Profile).
                profile = util.get_pybb_profile(request.user)
            except ObjectDoesNotExist:
                # Ok, we should create new profile for this user
                # and grant permissions for add posts
                # It should be caused rarely, so we move import signal here
                # to prevent circular import
                from pybb.models import user_saved
                user_saved(request.user, created=True)
                profile = util.get_pybb_profile(request.user)

            language = translation.get_language_from_request(request)

            if not profile.language:
                profile.language = language
                profile.save()

            if profile.language and profile.language != language:
                request.session['django_language'] = profile.language
                translation.activate(profile.language)
                request.LANGUAGE_CODE = translation.get_language()
Пример #23
0
 def process_request(self, request):
     try:
         language = request.COOKIES['language']
     except:
         language = translation.get_language_from_request(request)
     translation.activate(language)
     request.LANGUAGE_CODE = language
Пример #24
0
def get_obj_from_request(model, request,
                         pk_url_kwarg='pk',
                         slug_url_kwarg='slug',
                         slug_field='slug'):
    """
    Given a model and the request, try to extract and return an object
    from an available 'pk' or 'slug', or return None.

    Note that no checking is done that the view's kwargs really are for objects
    matching the provided model (how would it?) so use only where appropriate.
    """
    language = get_language_from_request(request, check_path=True)
    kwargs = request.resolver_match.kwargs
    mgr = model.objects
    if pk_url_kwarg in kwargs:
        return mgr.filter(pk=kwargs[pk_url_kwarg]).first()
    elif slug_url_kwarg in kwargs:
        # If the model is translatable, and the given slug is a translated
        # field, then find it the Parler way.
        filter_kwargs = {slug_field: kwargs[slug_url_kwarg]}
        translated_fields = model._parler_meta.get_translated_fields()
        if (issubclass(model, TranslatableModel) and
                slug_url_kwarg in translated_fields):
            return mgr.active_translations(language, **filter_kwargs).first()
        else:
            # OK, do it the normal way.
            return mgr.filter(**filter_kwargs).first()
    else:
        return None
Пример #25
0
    def get_context_data(self, **kwargs):
        ctx = super(EventDatesView, self).get_context_data(**kwargs)

        today = timezone.now().date()
        year = ctx.get('year', today.year)
        month = ctx.get('month', today.month)

        # Get plugin if possible so we can use language and namespace from
        # plugin, if not possible get namespace from view, language from
        # request
        try:
            pk = self.request.GET['plugin_pk'] or None
            plugin = EventCalendarPlugin.objects.get(pk=pk)
        except (EventCalendarPlugin.DoesNotExist, KeyError):
            namespace = self.namespace
            language = get_language_from_request(self.request, check_path=True)
        else:
            namespace = plugin.app_config.namespace
            language = plugin.language

        # calendar is the calendar tag
        site_id = getattr(get_current_site(self.request), 'id')
        ctx['calendar_tag'] = build_calendar_context(
            year, month, language, namespace, site_id
        )
        return ctx
Пример #26
0
 def process_request(self, request):
         path=request.META["PATH_INFO"]
         for nol in noLocalePath:
                 if path.find(nol)==0:
                         request.isLocaled=False
                         return
         #print path
         request.isLocaled=True
         language = translation.get_language_from_request(request)
         translation.activate(language)
         try:
            from mysite.urls import surl
            from base.models import appOptions
            from dbapp.urls import dbapp_url
            request.surl=surl
            request.dbapp_url=dbapp_url
            cache_title=cache.get("browse_title")
            if cache_title:
                 request.browse_title=cache_title
            else:
                 request.browse_title=appOptions["browse_title"]
                 cache.set("browse_title",appOptions["browse_title"],24*60*60)
         except Exception ,e:
             from traceback import print_exc
             print print_exc()
             pass
Пример #27
0
 def render_html(self, product, postfix):
     """
     Return a HTML snippet containing a rendered summary for this product.
     Build a template search path with `postfix` distinction.
     """
     if not self.label:
         msg = "The Product Serializer must be configured using a `label` field."
         raise exceptions.ImproperlyConfigured(msg)
     app_label = product._meta.app_label.lower()
     product_type = product.__class__.__name__.lower()
     request = self.context["request"]
     cache_key = "product:{0}|{1}-{2}-{3}-{4}-{5}".format(
         product.id, app_label, self.label, product_type, postfix, get_language_from_request(request)
     )
     content = cache.get(cache_key)
     if content:
         return mark_safe(content)
     params = [
         (app_label, self.label, product_type, postfix),
         (app_label, self.label, "product", postfix),
         ("shop", self.label, "product", postfix),
     ]
     try:
         template = select_template(["{0}/products/{1}-{2}-{3}.html".format(*p) for p in params])
     except TemplateDoesNotExist:
         return SafeText("<!-- no such template: '{0}/products/{1}-{2}-{3}.html' -->".format(*params[0]))
     # when rendering emails, we require an absolute URI, so that media can be accessed from
     # the mail client
     absolute_base_uri = request.build_absolute_uri("/").rstrip("/")
     context = RequestContext(request, {"product": product, "ABSOLUTE_BASE_URI": absolute_base_uri})
     content = strip_spaces_between_tags(template.render(context).strip())
     cache.set(cache_key, content, shop_settings.CACHE_DURATIONS["product_html_snippet"])
     return mark_safe(content)
Пример #28
0
 def _find_remote_autoplay_language(self, request):
     language = None
     if request.user.is_anonymous() or request.user.preferred_language == '':
         language = translation.get_language_from_request(request)
     else:
         language = request.user.preferred_language
     return language if language != '' else None
Пример #29
0
 def get_on_delete_redirect_url(self, event):
     language = getattr(
         self, 'current_lang', get_language_from_request(
             self.request, check_path=True))
     with force_language(language):
         return reverse('{0}:events_list'.format(
             event.app_config.namespace))
Пример #30
0
 def get_context(self, request, **kwargs):
     filter_kwargs = {'id': request.data.get('id')}
     if hasattr(self.product_model, 'translations'):
         filter_kwargs.update(translations__language_code=get_language_from_request(self.request))
     queryset = self.product_model.objects.filter(self.limit_choices_to, **filter_kwargs)
     product = get_object_or_404(queryset)
     return {self.product_field: product, 'request': request}
Пример #31
0
 def create(cls, request=None, **kwargs):
     create_email = kwargs.pop("create_email", True)
     confirm_email = kwargs.pop("confirm_email", None)
     account = cls(**kwargs)
     if "language" not in kwargs:
         if request is None:
             account.language = DEFAULT_LANGUAGE
         else:
             account.language = translation.get_language_from_request(request, check_path=True)
     account.save()
     if create_email and account.user.email:
         kwargs = {"primary": True}
         if confirm_email is not None:
             kwargs["confirm"] = confirm_email
         EmailAddress.objects.add_email(account.user, account.user.email, **kwargs)
     return account
Пример #32
0
 def get_form_kwargs(self, step=None):
     """This is called by self.get_form()"""
     kwargs = super(WizardCreateView, self).get_form_kwargs()
     kwargs['wizard_user'] = self.request.user
     if self.is_second_step(step):
         kwargs['wizard_page'] = self.get_origin_page()
         kwargs['wizard_language'] = self.get_origin_language()
     else:
         page_pk = self.page_pk or self.request.GET.get('page', None)
         if page_pk and page_pk != 'None':
             kwargs['wizard_page'] = Page.objects.filter(pk=page_pk).first()
         else:
             kwargs['wizard_page'] = None
         kwargs['wizard_language'] = self.request.GET.get(
             'language', get_language_from_request(self.request))
     return kwargs
Пример #33
0
 def process_request(self, request):
     if isinstance(request.user, AnonymousUser):
         # Anonymous users don't have preferences
         language = "auto"
         request.theme = settings.DEFAULT_THEME
         request.pagesize = settings.DEFAULT_PAGESIZE
     else:
         language = request.user.language
         request.theme = request.user.theme or settings.DEFAULT_THEME
         request.pagesize = request.user.pagesize or settings.DEFAULT_PAGESIZE
     if language == "auto":
         language = translation.get_language_from_request(request)
     if translation.get_language() != language:
         translation.activate(language)
     request.LANGUAGE_CODE = translation.get_language()
     request.charset = settings.DEFAULT_CHARSET
Пример #34
0
def preferences(request):
    if request.method == 'POST':
        form = PreferencesForm(request.POST)
        form.user = request.user
        if form.is_valid():
            try:
                newdata = form.cleaned_data
                request.user.language = newdata['language']
                request.user.theme = newdata['theme']
                request.user.pagesize = newdata['pagesize']
                if newdata['cur_password']:
                    request.user.set_password(newdata["new_password1"])
                    # Updating the password logs out all other sessions for the user
                    # except the current one if
                    # django.contrib.auth.middleware.SessionAuthenticationMiddleware
                    # is enabled.
                    update_session_auth_hash(request, form.user)
                request.user.save()
                # Switch to the new theme and language immediately
                request.theme = newdata['theme']
                if newdata['language'] == 'auto':
                    newdata[
                        'language'] = translation.get_language_from_request(
                            request)
                if translation.get_language() != newdata['language']:
                    translation.activate(newdata['language'])
                    request.LANGUAGE_CODE = translation.get_language()
                messages.add_message(
                    request, messages.INFO,
                    force_text(_('Successfully updated preferences')))
            except Exception as e:
                logger.error("Failure updating preferences: %s" % e)
                messages.add_message(
                    request, messages.ERROR,
                    force_text(_('Failure updating preferences')))
    else:
        pref = request.user
        form = PreferencesForm({
            'language': pref.language,
            'theme': pref.theme,
            'pagesize': pref.pagesize,
        })
    return render_to_response('common/preferences.html', {
        'title': _('Edit my preferences'),
        'form': form,
    },
                              context_instance=RequestContext(request))
Пример #35
0
    def list(self, request, version):
        """
        Person search endpoint: pass query params to ElasticSearch so it filters
        persons and returns a list of matching items
        """
        # Instantiate the form to allow validation/cleaning
        params_form = self._meta.indexer.form(data=request.query_params)

        # Return a 400 with error information if the query params are not valid
        if not params_form.is_valid():
            return Response(status=400, data={"errors": params_form.errors})

        limit, offset, query = params_form.build_es_query()

        query["sort"] = [
            {f"title_raw.{get_language_from_request(request)}": {"order": "asc"}}
        ]

        # pylint: disable=unexpected-keyword-arg
        search_query_response = ES_CLIENT.search(
            _source=getattr(self._meta.indexer, "display_fields", "*"),
            index=self._meta.indexer.index_name,
            body=query,
            # Directly pass meta-params through as arguments to the ES client
            from_=offset,
            size=limit or getattr(settings, "RICHIE_ES_PAGE_SIZE", ES_PAGE_SIZE),
        )

        # Format the response in a consumer-friendly way
        # NB: if there are 0 hits the query response is formatted the exact same way, only the
        # .hits.hits array is empty.
        response_object = {
            "meta": {
                "count": len(search_query_response["hits"]["hits"]),
                "offset": offset,
                "total_count": search_query_response["hits"]["total"]["value"],
            },
            "objects": [
                self._meta.indexer.format_es_object_for_api(
                    person,
                    # Get the best language to return multilingual fields
                    get_language_from_request(request),
                )
                for person in search_query_response["hits"]["hits"]
            ],
        }
        return Response(response_object)
Пример #36
0
    def redirect_homepage(self, request):
        if request.path not in settings.REDIRECTED_PATHS:
            return

        language = get_language_from_request(request)

        if language not in self.LANGUAGES:
            language = settings.DEFAULT_LANGUAGE

        querystring = request.META.get('QUERY_STRING', '')
        if querystring:
            querystring = '?' + querystring

        return HttpResponseRedirect(''.join([
            'http://', language, '.', settings.BASE_DOMAIN, request.path,
            querystring
        ]))
Пример #37
0
def cart_modal(request):
    try:
        translation.activate(translation.get_language_from_request(request))

        cart_obj = CartService(request).cart_model
        cart_products = cart_obj.products.all()

        return HttpResponse(status=200,
                            content=render_to_string("cart/cart_modal.html",
                                                     context={
                                                         'cart':
                                                         cart_obj,
                                                         'cart_products':
                                                         cart_products
                                                     }))
    except ObjectDoesNotExist:
        return HttpResponseBadRequest()
Пример #38
0
def hobbies(request):
    if 'color' in request.COOKIES.keys() and 'color2' in request.COOKIES.keys() and 'colorbw' in request.COOKIES.keys():
        color = request.COOKIES['color']
        color2 = request.COOKIES['color2']
        colorbw = request.COOKIES['colorbw']
    else:
        resp = HttpResponse('')
        color = '#9DCC1E'
        color2 = '#4F660F'
        colorbw = '#FFFFFF'
        resp.set_cookie('color',color)
        resp.set_cookie('color2',color2)
        resp.set_cookie('color',colorbw)
    rubix = video.objects.all().get(pk=4)
    maxit = video.objects.all().get(pk=5)
    lang = translation.get_language_from_request(request)
    return render(request, 'hobbies.html', {'name':'Jan', 'color':color, 'color2':color2, 'colorbw':colorbw, 'rubix':rubix, 'maxit':maxit, 'lang':lang})
Пример #39
0
    def get_extra_placeholder_menu_items(cls, request, placeholder):
        data = {
            'placeholder': placeholder.pk,
            'language': get_language_from_request(request, check_path=True),
        }
        endpoint = add_url_parameters(admin_reverse(CREATE_ALIAS_URL_NAME),
                                      **data)

        menu_items = [
            PluginMenuItem(
                _('Create Alias'),
                endpoint,
                action='modal',
                attributes={'icon': 'alias'},
            ),
        ]
        return menu_items
Пример #40
0
    def perform_mutate(cls, form, info):
        request = info.context
        scf = get_scaffolding(request)
        if not scaffolding_has_rental_history_request_info(scf):
            cls.log(
                info,
                "User has not completed the rental history form, aborting mutation."
            )
            return cls.make_error(
                "You haven't completed all the previous steps yet.")

        rhr = models.RentalHistoryRequest(
            first_name=scf.first_name,
            last_name=scf.last_name,
            apartment_number=scf.apt_number,
            phone_number=scf.phone_number,
            address=scf.street,
            address_verified=scf.address_verified,
            borough=scf.borough,
            zipcode=scf.zip_code,
        )
        rhr.set_user(request.user)
        rhr.full_clean()
        rhr.save()
        slack.sendmsg_async(get_slack_notify_text(rhr), is_safe=True)

        email = react_render_email(
            SITE_CHOICES.JUSTFIX,
            project.locales.DEFAULT,
            "rh/email-to-dhcr.txt",
            session=request.session,
        )
        email_dhcr.send_email_to_dhcr(email.subject, email.body)
        trigger_followup_campaign_async(
            f"{scf.first_name} {scf.last_name}",
            scf.phone_number,
            "RH",
            locale=translation.get_language_from_request(request,
                                                         check_path=True),
        )

        # Note that we used to purge the scaffolding information here, but lots
        # of users go on to create an account after this, and we don't want them
        # to have to re-enter all their information, so we'll keep it around.

        return cls.mutation_success()
Пример #41
0
def calendar(context, year, month, language=None, namespace=None):
    template_name = 'aldryn_events/includes/calendar.html'
    if not namespace:
        namespace, config = get_app_instance(context['request'])
    if not language:
        language = get_language_from_request(context['request'],
                                             check_path=True)
    t = get_template(template_name)
    try:
        EventsConfig.objects.get(namespace=namespace)
    except EventsConfig.DoesNotExist:
        context['namespace_error'] = ERROR_MESSAGE.format(namespace)
    else:
        context['calendar_tag'] = build_calendar_context(
            year, month, language, namespace)
    rendered = t.render(context.flatten())
    return rendered
Пример #42
0
def climate_for_city(request, city):
    weather_object = None
    language = get_language_from_request( request )
    weather_service = OpenWeatherService( settings.OPENWEATHER_URL, q=city,
                                          appid=settings.WEATHER_KEY, units="metric", lang=language )


    loop = asyncio.new_event_loop()
    asyncio.set_event_loop( loop )
    weather_object = loop.run_until_complete( weather_service.get_async_data() )
    if not weather_object:
        messages.error( request, _( 'Please enter valid city name' ) )
        return redirect( climate )
    args = {
        "weather_object": weather_object
    }
    return render( request, 'weather/climate-city.html', args )
Пример #43
0
def moduleview(request, course=None, module=None):
    lang = get_language_from_request(request)
    if course:
        try:
            c = Course.objects.language(lang).get(slug=course)
        except Course.DoesNotExist:
            c = None
    else:
        c = None
    try:
        m = Module.objects.language(lang).get(slug=module)
    except Module.DoesNotExist:
        return HttpResponseNotFound()
    c = {"module": m, "instance": m, "course": c}
    return render_to_response("courses/module.html",
                              c,
                              context_instance=RequestContext(request))
 def populate(self):
     # setup the extension toolbar with permissions and sanity checks
     current_page_menu = self._setup_extension_toolbar()
     # if it's all ok
     if current_page_menu and self.toolbar.edit_mode:
         # retrieves the instances of the current title extension (if any) and the toolbar item url
         lang = get_language_from_request(self.request, check_path=True)
         print lang
         urls = self.get_title_extension_admin(lang)
         print urls
         # cycle through the title list
         for title_extension, url in urls:
             # adds toolbar items
             current_page_menu.add_modal_item(
                 'SEO Keywords',
                 url=url,
                 disabled=not self.toolbar.edit_mode)
Пример #45
0
    def save(self, commit=True):
        social_account = super(AdvertSocialAccountForm,
                               self).save(commit=False)

        social_network = SocialNetwork.get_social_network(
            link=social_account.link)
        social_account.social_network = social_network

        external_logo = self.cleaned_data['external_logo']

        if external_logo:
            social_account.logo.save(external_logo._origin_name, external_logo,
                                     False)

        if social_account.pk is None or 'link' in self.changed_data:
            if social_account.pk is None:
                phrase_obj = Phrase.get_rand_phrase(
                    get_language_from_request(self.request))

                if phrase_obj is not None:
                    social_account.confirmation_code = phrase_obj.phrase
                else:
                    social_account.confirmation_code = get_random_string(
                        length=32)

            social_account_confirm_link = self.request.session.get(
                'social_account_confirm_link', None)
            social_account_confirm_status = self.request.session.get(
                'social_account_confirm_status', None)

            if (social_account_confirm_link is not None
                    and social_account_confirm_status is not None
                    and social_account.link == social_account_confirm_link):
                social_account.confirmed = bool(social_account_confirm_status)
            else:
                social_account.confirmed = False

        if commit:
            social_account.save()

            if 'social_account_confirm_link' in self.request.session:
                del self.request.session['social_account_confirm_link']
            if 'social_account_confirm_status' in self.request.session:
                del self.request.session['social_account_confirm_status']
        return social_account
Пример #46
0
    def get_extra_plugin_menu_items(cls, request, plugin):
        if plugin.plugin_type == cls.__name__:
            edit_endpoint = plugin.alias.get_absolute_url()
            detach_endpoint = admin_reverse(
                DETACH_ALIAS_PLUGIN_URL_NAME,
                args=[plugin.pk],
            )

            plugin_menu_items = [
                PluginMenuItem(
                    _('Edit Alias'),
                    edit_endpoint,
                    action='',
                    attributes={'icon': 'alias'},
                ),
            ]

            if cls.can_detach(
                    request.user,
                    plugin.placeholder,
                    plugin.alias.get_plugins(),
            ):
                plugin_menu_items.append(
                    PluginMenuItem(
                        _('Detach Alias'),
                        detach_endpoint,
                        action='modal',
                        attributes={'icon': 'alias'},
                    ))
            return plugin_menu_items

        data = {
            'plugin': plugin.pk,
            'language': get_language_from_request(request, check_path=True),
        }
        endpoint = add_url_parameters(admin_reverse(CREATE_ALIAS_URL_NAME),
                                      **data)
        return [
            PluginMenuItem(
                _('Create Alias'),
                endpoint,
                action='modal',
                attributes={'icon': 'alias'},
            ),
        ]
Пример #47
0
    def dispatch(self, request, *args, **kwargs):
        self.namespace, self.config = get_app_instance(request)
        language = get_language_from_request(request, check_path=True)
        self.queryset = (Event.objects.namespace(
            self.namespace).published().language(language).order_by(
                *ORDERING_FIELDS))
        self.event = self.queryset.active_translations(
            language, slug=kwargs['slug']).first()
        if not self.event:
            raise Http404("Event not found")

        set_language_changer(request, self.event.get_absolute_url)
        setattr(self.request, request_events_event_identifier, self.event)

        if hasattr(request, 'toolbar'):
            request.toolbar.set_object(self.event)

        return super(EventDetailView, self).dispatch(request, *args, **kwargs)
Пример #48
0
    def process_request(self, request):
        if request.path_info in IGNORE:
            return

        locale, path = self.split_locale_from_request(request)
        locale_path = utils.locale_path(path, locale or translation.get_language_from_request(request) \
                                        or translation.get_language())

        if locale_path != request.path_info:
            if request.META.get("QUERY_STRING", ""):
                locale_path = "%s?%s" % (locale_path,
                                         request.META['QUERY_STRING'])
            return HttpResponseRedirect(locale_path)
        request.path_info = path
        if not locale:
            locale = translation.get_language() or settings.LANGUAGE_CODE
        translation.activate(locale)
        request.LANGUAGE_CODE = translation.get_language()
Пример #49
0
def language(request):
    """
    Sets language depending on the profile.
    """

    language = get_language_from_request(request)
    content = {
        'lan': language if language else settings.LANGUAGE_CODE,
        'languages': dict(settings.LANGUAGES).keys(),
    }

    if request.user.is_authenticated:
        # Optimizacion of language selector
        language = Profile.objects.filter(user_id=request.user.id).values_list(
            'language', flat=True).first()
        content['lan'] = language
        return content
    return content
Пример #50
0
    def process_request(request):
        full_path_parts = request.get_full_path().split('/')
        request_lang = None

        if len(full_path_parts) > 2 and len(full_path_parts[1]) == 2:
            request_lang = full_path_parts[1]

        lang = (request_lang or translation.get_language_from_request(
            request, check_path=False) or settings.DEFAULT_LANGUAGE).lower()

        available_langs = settings.LANGUAGE_CODES_PUBLIC
        if lang not in available_langs:
            raise Http404(_('Язык "%s" не зарегистрирован в системе') % lang)

        translation.activate(lang)
        request.LANGUAGE_CODE = lang
        request.session[settings.LANGUAGE_COOKIE_NAME] = lang
        return None
Пример #51
0
 def process_request(self, request):
     urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
     (
         i18n_patterns_used,
         prefixed_default_language,
     ) = is_language_prefix_patterns_used(urlconf)
     language = translation.get_language_from_request(
         request, check_path=i18n_patterns_used
     )
     language_from_path = translation.get_language_from_path(request.path_info)
     if (
         not language_from_path
         and i18n_patterns_used
         and not prefixed_default_language
     ):
         language = settings.LANGUAGE_CODE
     translation.activate(language)
     request.LANGUAGE_CODE = translation.get_language()
Пример #52
0
 def publish_post(self, request, pk):
     """
     Admin view to publish a single post
     :param request: request
     :param pk: primary key of the post to publish
     :return: Redirect to the post itself (if found) or fallback urls
     """
     language = get_language_from_request(request, check_path=True)
     try:
         post = News.objects.get(pk=int(pk))
         post.publish = True
         post.save()
         return HttpResponseRedirect(post.get_absolute_url(language))
     except Exception:
         try:
             return HttpResponseRedirect(request.META['HTTP_REFERER'])
         except KeyError:
             return HttpResponseRedirect(reverse('oscar_news:posts-latest'))
Пример #53
0
 def get_context_data(self, **kwargs):
     context = super(NavigationMixin, self).get_context_data(**kwargs)
     language = get_language_from_request(self.request, check_path=True)
     events_by_year = build_events_by_year(
         events=(Event.objects.namespace(self.namespace).future().
                 active_translations(language).language(language)))
     context['events_by_year'] = events_by_year
     archived_events_by_year = build_events_by_year(
         events=(Event.objects.namespace(
             self.namespace).archive().active_translations(
                 language).language(language)),
         is_archive_view=True,
     )
     context['archived_events_by_year'] = archived_events_by_year
     context['event_year'] = self.kwargs.get('year')
     context['event_month'] = self.kwargs.get('month')
     context['event_day'] = self.kwargs.get('day')
     return context
Пример #54
0
 def render_to_response(self, context, **response_kwargs):
     try:
         author = EtherpadAuthor.objects.get(user=self.request.user)
     except EtherpadAuthor.DoesNotExist:
         author = None
     if author is None or not self.object.group in author.group.all():
         raise PermissionDenied
     response = super(EtherPadEditView,
                      self).render_to_response(context, **response_kwargs)
     expires = datetime.datetime.utcnow() + datetime.timedelta(
         seconds=SESS_LENGTH)
     client = EtherpadLiteClient(
         base_params={'apikey': settings.ETHERPAD_API_KEY},
         base_url=settings.ETHERPAD_INTERNAL_URL)
     result = client.createSession(groupID=self.object.group.etherpad_id,
                                   authorID=author.etherpad_id,
                                   validUntil=time.mktime(
                                       expires.timetuple()).__str__())
     # Delete the existing session first (if there is any)
     if ('padSessionID' and 'sessionID' in self.request.COOKIES):
         try:
             client.deleteSession(
                 sessionID=self.request.COOKIES['sessionID'])
         except EtherpadException:
             pass
         response.delete_cookie('sessionID')
         response.delete_cookie('padSessionID')
     # Set the new session cookie for both the server and the local site
     # This will not work if etherpad-lite is running on external host.
     # TODO: we probably should set cookie for server.external_url
     response.set_cookie('sessionID',
                         value=result['sessionID'],
                         expires=expires,
                         httponly=False)
     response.set_cookie('padSessionID',
                         value=result['sessionID'],
                         expires=expires,
                         httponly=False)
     response.set_cookie('language',
                         value=translation.get_language_from_request(
                             self.request),
                         expires=expires,
                         httponly=False)
     return response
Пример #55
0
 def render(self,
            request,
            place,
            context,
            block_content_relation=None,
            *args,
            **kwargs):
     language_get = request.GET.get('set_language', None)
     # if we just change the language, get_language_from_request function does
     # not work fine, so first we check if the language have changed now
     language = language_get or get_language_from_request(request)
     return self.render_block(
         request,
         template_name='googlesearch/block_googlesearch.html',
         block_title=_('Search'),
         context={
             'plugin_config': self.get_config(),
             'language': language
         })
Пример #56
0
    def test_admin_set_trad(self):
        # Given no DifficultyLevel is present in the database
        self.assertEquals(DifficultyLevel.objects.all().count(), 0)

        # login
        success = login_from_cred(self.client, self.cred)
        self.assertTrue(success)

        add_difficulty_url = admin_add_url_from_model(DifficultyLevel)

        response = self.client.get(add_difficulty_url)
        self.assertEquals(response.status_code, 200)

        # Get data for DifficultyLevel creation and create it through admin view
        data = self.get_dummy_data_trad()

        response = self.client.post(add_difficulty_url, data, follow=True)
        self.assertRedirects(response,
                             admin_list_url_from_model(DifficultyLevel))
        self.assertEquals(response.status_code, 200)

        iss = DifficultyLevel.objects.all()
        self.assertEquals(
            len(iss), 1, "One and only one DifficultyLevel should be created")

        # This may test too much.
        # Test language translation for DifficultyLevel.difficulty works
        # Given the language set, it returns the appropriate version (fr, it, en)

        orig_language = translation.get_language_from_request(
            response._request)
        restore_language = lambda: translation.activate(orig_language)

        difficulty_trad = self.get_dummy_data_trad()
        intervention_difficulty = iss[0]

        for language in ('fr', 'it', 'en'):
            translation.activate(language)
            translated_difficulty = difficulty_trad['difficulty_%s' % language]
            self.assertEquals(intervention_difficulty.difficulty,
                              translated_difficulty)

        restore_language()
Пример #57
0
def create_order(request):
    if request.method == 'POST':
        if CartService.exists(request):
            form = OrderForm(request.POST)
            if form.is_valid():
                cart_service = CartService(request)
                lang_code = get_language_from_request(request)

                cart_service.check_out(request)
                OrderServices.create_order(cart_service.cart_model, form,
                                           lang_code)
                return redirect('successful_order')
            else:
                return HttpResponse(form.errors.as_json(), status=400)

        else:
            return HttpResponseBadRequest("cart not found")
    else:
        return HttpResponseBadRequest()
Пример #58
0
 def process_request(self, request):
     query_language = request.GET.get('hl')
     if query_language:
         language = query_language
         lang_codes = set(lang[0][:2] for lang in settings.LANGUAGES)
         if language[:2] not in lang_codes:
             url = remove_query_param_from_url(request.get_full_path(),
                                               'hl')
             return render_to_response('404.html',
                                       {'url_without_language': url},
                                       status=404)
     elif hasattr(
             request, 'user'
     ) and request.user.is_authenticated and not request.user.is_anonymous:
         language = request.user.userprofile.language
     else:
         language = translation.get_language_from_request(request)
     translation.activate(language)
     request.LANGUAGE_CODE = translation.get_language()
Пример #59
0
    def get_lang_version(self, request=None):
        if request is not None:
            lang = get_language_from_request(request)
            try:
                return self.language_versions.get(language=lang)
            except NodeLanguageVersion.DoesNotExist:
                pass

        try:
            return self.language_versions.get(language=get_language())
        except NodeLanguageVersion.DoesNotExist:
            pass

        try:
            return self.language_versions.get(language=settings.LANGUAGE_CODE)
        except NodeLanguageVersion.DoesNotExist:
            pass

        return self.language_versions.first()
Пример #60
0
 def process_request(self, request):
     language = translation.get_language_from_request(request)
     requested_language = request.REQUEST.get('language', None)
     if requested_language and requested_language != language \
     and check_for_language(requested_language):
         language = requested_language
         if hasattr(request, 'session'):
             request.session['django_language'] = language
         else:
             next = request.REQUEST.get('next', None)
             if not next:
                 next = request.META.get('HTTP_REFERER', None)
             if not next:
                 next = '/'
             response = HttpResponseRedirect(next)
             response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language)
             return response
     translation.activate(language)
     request.LANGUAGE_CODE = translation.get_language()