示例#1
0
    def cache_key(self, template_name, *args):
        if len(args) > 0:  # Django >= 1.9
            key = super(CachedLoader, self).cache_key(template_name, *args)
        else:
            key = template_name

        return '{0}:{1}'.format(get_flavour(), key)
示例#2
0
    def test_set_flavour_with_session_backend(self):
        original_FLAVOURS_STORAGE_BACKEND = settings.FLAVOURS_STORAGE_BACKEND
        try:
            settings.FLAVOURS_STORAGE_BACKEND = 'session'
            request = Mock()
            request.session = {}
            set_flavour('mobile', request=request)
            self.assertEqual(request.session, {})
            set_flavour('mobile', request=request, permanent=True)
            self.assertEqual(request.session,
                             {settings.FLAVOURS_SESSION_KEY: u'mobile'})
            self.assertEqual(get_flavour(request), 'mobile')

            response = self.client.get('/')
            self.assertFalse('sessionid' in response.cookies)
            response = self.client.get(
                '/', {
                    settings.FLAVOURS_GET_PARAMETER: 'mobile',
                })
            self.assertTrue('sessionid' in response.cookies)
            sessionid = response.cookies['sessionid'].value
            session = Session.objects.get(session_key=sessionid)
            session_data = session.get_decoded()
            self.assertTrue(settings.FLAVOURS_SESSION_KEY in session_data)
            self.assertEqual(session_data[settings.FLAVOURS_SESSION_KEY],
                             'mobile')
        finally:
            settings.FLAVOURS_STORAGE_BACKEND = original_FLAVOURS_STORAGE_BACKEND
示例#3
0
    def test_set_flavour_with_session_backend(self):
        original_FLAVOURS_STORAGE_BACKEND = settings.FLAVOURS_STORAGE_BACKEND
        try:
            settings.FLAVOURS_STORAGE_BACKEND = "session"
            request = Mock()
            request.session = {}
            set_flavour("mobile", request=request)
            self.assertEqual(request.session, {})
            set_flavour("mobile", request=request, permanent=True)
            self.assertEqual(
                request.session, {settings.FLAVOURS_SESSION_KEY: "mobile"}
            )
            self.assertEqual(get_flavour(request), "mobile")

            response = self.client.get("/")
            self.assertFalse("sessionid" in response.cookies)
            response = self.client.get(
                "/", {settings.FLAVOURS_GET_PARAMETER: "mobile",}
            )
            self.assertTrue("sessionid" in response.cookies)
            sessionid = response.cookies["sessionid"].value
            session = Session.objects.get(session_key=sessionid)
            session_data = session.get_decoded()
            self.assertTrue(settings.FLAVOURS_SESSION_KEY in session_data)
            self.assertEqual(session_data[settings.FLAVOURS_SESSION_KEY], "mobile")
        finally:
            settings.FLAVOURS_STORAGE_BACKEND = original_FLAVOURS_STORAGE_BACKEND
示例#4
0
def common(request):
    import settings
    context = {}
    context['ga_is_on'] = settings.GA_IS_ON
    context['siteurl'] = settings.SITE_URL
    context['sitename'] = settings.SITE_NAME
    context['base_template'] = settings.BASE_TEMPLATE
    if get_flavour(request) == 'mobile':
        context['base_template'] = settings.BASE_TEMPLATE_MOBILE
    
    show_sidebar = False
    if 'show_sidebar' in request.session:
        show_sidebar = ast.literal_eval(request.session['show_sidebar'])
    
    context['show_sidebar'] = show_sidebar
    
    
    # NOTIFICATIONS
    if request.user.is_authenticated():
    
        test_items = request.session.get('TEST_NOTIFICATIONS', len(request.user.get_test_items()))
        review_items = request.session.get('TEST_NOTIFICATIONS', len(request.user.get_review_items()))
    
        context['review_notifications'] = review_items
        context['test_notifications'] = test_items
        context['total_notifications'] = test_items + review_items
        
    

    return context
示例#5
0
def team_page(request, team_name):
    team = Roster.objects.get(team_name=team_name)
    rosters = Roster.objects.all().order_by('rank')
    # Stats Table
    stats = Stats.objects.filter(team=team_name)
    statsTable = StatsTable(stats)
    # Current Challenges Table
    currentChallenges = Challenge.objects.filter(
        Q(challenger=team.id) | Q(challenged=team.id)).filter(played=False)
    currentTable = CurrentChallenges(currentChallenges,
                                     empty_text="No current challenges!")
    # Challengers Table
    challengersTable = get_challengers(team)
    # Recent Games
    recentGames = get_recent_games(team)
    # Page template either for browser or mobile
    flavour = get_flavour()
    page = 'team_page.html' if flavour == 'full' else 'team_page_mobile.html'
    return render(
        request,
        page,
        {
            'team': team,
            'stats': stats,
            'rosters': rosters,  # for sidebar
            'statsTable': statsTable,
            'currentTable': currentTable,
            'challengersTable': challengersTable,
            'recentGames': recentGames,
            'rank': int(team.rank),  # for pageheader coloring
        })
示例#6
0
def iframe(request, videoid):
    """Generate an iframe with a player for this video"""

    try:
        gloss = Gloss.objects.get(pk=videoid)
        glossvideo = gloss.get_video()

        if django_mobile.get_flavour(request) == 'mobile':
            videourl = glossvideo.get_mobile_url()
        else:
            videourl = glossvideo.get_absolute_url()

        posterurl = glossvideo.poster_url()
    except:
        gloss = None
        glossvideo = None
        videourl = None
        posterurl = None

    return render_to_response("iframe.html", {
        'videourl': videourl,
        'posterurl': posterurl,
        'aspectRatio': settings.VIDEO_ASPECT_RATIO,
    },
                              context_instance=RequestContext(request))
示例#7
0
def iframe(request, videoid):
    """Generate an iframe with a player for this video"""
    
    try:
        gloss = Gloss.objects.get(pk=videoid)
        glossvideo = gloss.get_video()
        
        if django_mobile.get_flavour(request) == 'mobile':
            videourl = glossvideo.get_mobile_url()
        else:
            videourl = glossvideo.get_absolute_url()
                
        posterurl = glossvideo.poster_url()
    except:
        gloss = None
        glossvideo = None
        videourl = None
        posterurl = None


    return render_to_response("iframe.html",
                              {'videourl': videourl,
                               'posterurl': posterurl,
                               'aspectRatio': settings.VIDEO_ASPECT_RATIO,
                               },
                               context_instance=RequestContext(request))
示例#8
0
 def test_set_default_flavour(self):
     request = Mock()
     request.GET = {}
     middleware = SetFlavourMiddleware()
     middleware.process_request(request)
     # default flavour is set
     self.assertEqual(get_flavour(), "full")
示例#9
0
    def test_set_flavour_with_session_backend(self):
        original_FLAVOURS_STORAGE_BACKEND = settings.FLAVOURS_STORAGE_BACKEND
        try:
            settings.FLAVOURS_STORAGE_BACKEND = 'session'
            request = Mock()
            request.session = {}
            set_flavour('mobile', request=request)
            self.assertEqual(request.session, {})
            set_flavour('mobile', request=request, permanent=True)
            self.assertEqual(request.session, {
                settings.FLAVOURS_SESSION_KEY: u'mobile'
            })
            self.assertEqual(get_flavour(request), 'mobile')

            response = self.client.get('/')
            self.assertFalse('sessionid' in response.cookies)
            response = self.client.get('/', {
                settings.FLAVOURS_GET_PARAMETER: 'mobile',
            })
            self.assertTrue('sessionid' in response.cookies)
            sessionid = response.cookies['sessionid'].value
            session = Session.objects.get(session_key=sessionid)
            session_data = session.get_decoded()
            self.assertTrue(settings.FLAVOURS_SESSION_KEY in session_data)
            self.assertEqual(session_data[settings.FLAVOURS_SESSION_KEY], 'mobile')
        finally:
            settings.FLAVOURS_STORAGE_BACKEND = original_FLAVOURS_STORAGE_BACKEND
示例#10
0
 def test_set_default_flavour(self):
     request = Mock()
     request.META = MagicMock()
     request.GET = {}
     middleware = SetFlavourMiddleware()
     middleware.process_request(request)
     # default flavour is set
     self.assertEqual(get_flavour(), 'full')
示例#11
0
文件: views.py 项目: mkao006/aws_test
def index(request):
    """
    Detect device and return the home page
    """
    if get_flavour() != 'full':
        return render(request, 'random_walker/m_index.html')
    else:
        return render(request, 'random_walker/index.html')
示例#12
0
def index(request):
    """
    Returns the Random Walker web page according to device
    """

    if get_flavour() != 'full':
        return render(request, 'random_walker_engine/_m_random_walker_engine.html')
    else:
        return render(request, 'random_walker_engine/_random_walker_engine.html')
示例#13
0
def login_view(request):
    """
    Page for loging
    """
    form = AuthenticationForm()
    if get_flavour() != 'full':
        return render(request, 'user_action/_m_login.html', {'form': form})
    else:
        return render(request, 'user_action/_login.html', {'form': form})
示例#14
0
def publications(request):
    DEFAULT_PUB = settings.DEFAULT_PUB
    try:
        default_pub = Publication.objects.get(slug=DEFAULT_PUB)
    except Publication.DoesNotExist:
        default_pub = None

    result = {
        'BASE_SUB':
        settings.BASE_SUB,
        'DEFAULT_PUB':
        DEFAULT_PUB,
        'default_pub':
        default_pub,
        'custom_icons_publications':
        getattr(settings, 'CORE_CUSTOM_ICONS_PUBLICATIONS', None),
    }

    for p in Publication.objects.exclude(slug=DEFAULT_PUB).iterator():
        slug_var = p.slug.replace('-', '_')
        result.update({
            slug_var.upper() + '_SUB': p.slug,
            slug_var + '_pub': p
        })

    if get_flavour(request) == 'amp':
        result['extra_header_template'] = getattr(
            settings, 'HOMEV3_EXTRA_HEADER_TEMPLATE_AMP', None)
    else:
        result['extra_header_template'] = getattr(
            settings, 'HOMEV3_EXTRA_HEADER_TEMPLATE', None)
        result['footer_template'] = settings.HOMEV3_FOOTER_TEMPLATE

    # use this context processor to load also some other useful variables configured in settings
    result.update(((var, getattr(settings, var, None)) for var in (
        'HOMEV3_CUSTOM_CSS',
        'HOMEV3_CUSTOM_PRINT_CSS',
        'HOMEV3_LOGO',
        'HOMEV3_LOGO_WIDTH',
        'HOMEV3_SECONDARY_LOGO',
        'HOMEV3_LOGO_FOOTER',
        'HOMEV3_LOGO_FOOTER_WIDTH',
        'HOMEV3_LOGO_PRINTABLE',
        'HOMEV3_LOGO_PRINTABLE_WIDTH',
        'HOMEV3_LOGO_ALT_TEXT',
        'HOMEV3_TWITTER_SITE_META',
        'HOMEV3_EXTRA_META',
        'HOMEV3_MENU_PUBLICATIONS_USE_HEADLINE',
        'CORE_ARTICLE_DETAIL_PUBLISHER_META',
        'CORE_ARTICLE_CARDS_DATE_PUBLISHED_USE_AGO',
        'CORE_ARTICLE_DETAIL_DATE_TOOLTIP',
        'CORE_ARTICLE_DETAIL_ALL_DATE_TOOLTIP',
        'CORE_ARTICLE_ENABLE_PHOTO_BYLINE',
        'PWA_MANIFEST_STATIC_PATH',
    )))

    return result
示例#15
0
def sign_up(request):
    """
    Page for sign up
    """
    form = RegistrationForm()
    if get_flavour() != 'full':
        return render(request, 'user_action/_m_sign_up.html', {'form': form})
    else:
        return render(request, 'user_action/_sign_up.html', {'form': form})
示例#16
0
 def __init__(self, *args, **kwargs):
     self.flavour = kwargs.pop('flavour', get_flavour())
     super(FullDateAndPlaceBird, self).__init__(*args, **kwargs)
     if self.flavour == 'mobile':
         self.fields['date'].widget = DateInput(attrs={
             'placeholder': 'введите дату рождения',
         })
         self.fields['time'].widget = TimeInput(attrs={
             'placeholder': 'введите время рождения',
         })
示例#17
0
    def process_request(self, request):
        _init_flavour(request)

        if settings.FLAVOURS_GET_PARAMETER in request.GET:
            flavour = request.GET[settings.FLAVOURS_GET_PARAMETER]
            if flavour in settings.FLAVOURS:
                set_flavour(flavour, request, permanent=True)
        else:
            flavour = get_flavour()
            set_flavour(flavour, request, permanent=True)
示例#18
0
    def cache_key(self, template_name, template_dirs, *args):
        if len(args) > 0:  # Django >= 1.9
            key = super(CachedLoader, self).cache_key(template_name, template_dirs, *args)
        else:
            if template_dirs:
                key = "-".join([template_name, hashlib.sha1(force_bytes("|".join(template_dirs))).hexdigest()])
            else:
                key = template_name

        return "{0}:{1}".format(get_flavour(), key)
示例#19
0
    def cache_key(self, template_name, template_dirs):
        if template_dirs:
            key = '-'.join([
                template_name,
                hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()
            ])
        else:
            key = template_name

        return '{0}:{1}'.format(get_flavour(), key)
示例#20
0
    def process_request(self, request):
        _init_flavour(request)

        if settings.FLAVOURS_GET_PARAMETER in request.GET:
            flavour = request.GET[settings.FLAVOURS_GET_PARAMETER]
            if flavour in settings.FLAVOURS:
                set_flavour(flavour, request, permanent=True)
        else:
            flavour = get_flavour()
            set_flavour(flavour, request, permanent=True)
示例#21
0
    def cache_key(self, template_name, template_dirs):
        if template_dirs:
            key = '-'.join([
                template_name,
                hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()
            ])
        else:
            key = template_name

        return '{0}:{1}'.format(get_flavour(), key)
示例#22
0
 def prepare_template_name(self, template_name):
     
     flavour = get_flavour()
     
     #if None is given as flavour (default), then don't create path to flavour
     if flavour: 
         template_name = u'%s/%s' % (flavour, template_name)
         if settings.FLAVOURS_TEMPLATE_PREFIX:
             template_name = settings.FLAVOURS_TEMPLATE_PREFIX + template_name
     
     return template_name
示例#23
0
def home(request):
    flavour = django_mobile.get_flavour(request)
    user_serializer = UserDetailSerializer(request.user)
    user_json = JSONRenderer().render(user_serializer.data)
    content,pager = api_retrieve(request,PostList)
    return render(request,'templates/home.html',{
        'user_json':user_json,
         'flavour':flavour,
        'pager_json':JSONRenderer().render(pager),
        'initial_data':content
    })
def common(request):
    from westiseast import settings
    context = {}
    context['ga_is_on'] = settings.GA_IS_ON

    context['base_template'] = settings.BASE_TEMPLATE

    if django_mobile.get_flavour(request) == 'mobile':
        context['base_template'] = settings.BASE_TEMPLATE_MOBILE

    return context
def common(request):
    from westiseast import settings
    context = {}
    context['ga_is_on'] = settings.GA_IS_ON
        
    context['base_template'] = settings.BASE_TEMPLATE
    
    if django_mobile.get_flavour(request) == 'mobile':    
        context['base_template'] = settings.BASE_TEMPLATE_MOBILE    
        
    return context
示例#26
0
def home(request):
    flavour = django_mobile.get_flavour(request)
    user_serializer = UserDetailSerializer(request.user)
    user_json = JSONRenderer().render(user_serializer.data)
    content, pager = api_retrieve(request, PostList)
    return render(
        request, 'templates/home.html', {
            'user_json': user_json,
            'flavour': flavour,
            'pager_json': JSONRenderer().render(pager),
            'initial_data': content
        })
示例#27
0
def get_request_cache_key(request, private=False):
    """
    Уникальный ключ для request
    @param private - уникальный ключ для каждого пользователя
    """
    md5 = hashlib.md5()
    md5.update(force_bytes(iri_to_uri(_get_full_path(request))))
    md5.update(force_bytes(_get_cookie_key(request, private)))
    md5.update(force_bytes(get_flavour(request)))
    if request.is_ajax():
        md5.update(force_bytes('ajax'))
    return md5.hexdigest()
示例#28
0
 def test_set_flavour_with_session_backend(self):
     original_FLAVOURS_STORAGE_BACKEND = settings.FLAVOURS_STORAGE_BACKEND
     try:
         settings.FLAVOURS_STORAGE_BACKEND = 'session'
         request = Mock()
         request.session = {}
         set_flavour('mobile', request=request)
         self.assertEqual(request.session, {})
         set_flavour('mobile', request=request, permanent=True)
         self.assertEqual(request.session, {settings.FLAVOURS_SESSION_KEY: 'mobile'})
         self.assertEqual(get_flavour(request), 'mobile')
     finally:
         settings.FLAVOURS_STORAGE_BACKEND = original_FLAVOURS_STORAGE_BACKEND
示例#29
0
def index(request):
	if django_mobile.get_flavour(request) == 'mobile':
		return render_to_response('index.html', context_instance=RequestContext(request))
	else:
		comming_events = Event.objects.filter(finished=False).order_by('start_date')[:20]
		repeated_points = {}
		for evx in comming_events:
			evp = (evx.lat, evx.lng)
			if (evp in repeated_points):
				repeated_points[evp] += 1
			else:
				repeated_points[evp] = 1
		return render_to_response('map.html', {'comming_events': comming_events, 'repeated_points': repeated_points}, context_instance=RequestContext(request))
示例#30
0
    def cache_key(self, template_name, template_dirs, *args):
        if len(args) > 0:  # Django >= 1.9
            key = super(CachedLoader, self).cache_key(template_name, template_dirs, *args)
        else:
            if template_dirs:
                key = '-'.join([
                    template_name,
                    hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()
                ])
            else:
                key = template_name

        return '{0}:{1}'.format(get_flavour(), key)
示例#31
0
 def test_set_flavour_with_cookie_backend(self):
     original_FLAVOURS_STORAGE_BACKEND = settings.FLAVOURS_STORAGE_BACKEND
     try:
         settings.FLAVOURS_STORAGE_BACKEND = 'cookie'
         request = Mock()
         request.COOKIES = {}
         set_flavour('mobile', request=request)
         self.assertEqual(request.COOKIES, {})
         set_flavour('mobile', request=request, permanent=True)
         self.assertEqual(request.COOKIES, {settings.FLAVOURS_COOKIE_KEY: 'mobile'})
         self.assertEqual(get_flavour(request), 'mobile')
     finally:
         settings.FLAVOURS_STORAGE_BACKEND = original_FLAVOURS_STORAGE_BACKEND
示例#32
0
def enter(request):
    """
    Renders and processes contest entry page
    """
    if request.COOKIES.has_key(CONTEST_COOKIE_KEY):
        return HttpResponseRedirect(reverse("contests_share"))

    try:
        now = datetime.now()
        contest = Contest.objects.filter(
            start_date__lte=now,
            end_date__gte=now,
        )[0]
    except IndexError:
        contest = None

    if contest is None:
        return render_to_response("contests/closed.html", {
            
        }, context_instance=RequestContext(request))

    if request.method == "POST":
        form = ContestEntryForm(request.POST, contest=contest)

        if form.is_valid():
            contest_entry = form.save(commit=False)
            contest_entry.contest = contest

            if get_flavour(request=request) == u"mobile":
                contest_entry.source = SOURCE_MOBILE
            else:
                contest_entry.source = SOURCE_DESKTOP

            contest_entry.save()

            response = HttpResponseRedirect(reverse("contests_share"))
            delta = contest.end_date - datetime.now()
            max_age = (delta.days * 24 * 60 * 60) + delta.seconds
            expiry = datetime.strftime(contest.end_date, "%a, %d-%b-%Y %H:%M:%S GMT")

            response.set_cookie(CONTEST_COOKIE_KEY, value="True", max_age=max_age, expires=expiry)
            response.set_cookie(CONTEST_FIRST_NAME_KEY, value=form.cleaned_data.get("first_name"), max_age=max_age, expires=expiry)

            return response
    else:
        form = ContestEntryForm()

    return render_to_response("contests/enter.html", {
        "form": form,
    }, context_instance=RequestContext(request))
示例#33
0
def mobile_switcher(request):
        if 'django_mobile' in INSTALLED_APPS:
            from django_mobile import set_flavour
            from django_mobile import get_flavour
        try:
            if get_flavour() == 'mobile':
                set_flavour('full', request=request, permanent=True)
            else:
                set_flavour('mobile', request=request, permanent=True)
            return HttpResponseRedirect(reverse('site-index'))
        except ValueError:
            return render(request, '404.html', {
                'alert': '"%s" is not a valid display option for this site.' % flavor
            })
示例#34
0
 def test_functional(self):
     from django.template.loader import render_to_string
     set_flavour('full')
     result = render_to_string('index.html')
     result = result.strip()
     self.assertEqual(result, 'Hello .')
     # simulate RequestContext
     result = render_to_string('index.html',
                               {'flavour': get_flavour(Mock())})
     result = result.strip()
     self.assertEqual(result, 'Hello full.')
     set_flavour('mobile')
     result = render_to_string('index.html')
     result = result.strip()
     self.assertEqual(result, 'Mobile!')
示例#35
0
def api_retrieve(request,api_class,*args,**kwargs):
    flavour = django_mobile.get_flavour(request)
    page_size = 12 if flavour == 'mobile' else 24
    pager ={}
    page = request.GET.get('page',1)
    page_size = request.GET.get(REST_FRAMEWORK['PAGINATE_BY_PARAM'],page_size)
    if page:
        pager['page'] = int(page)
    if page_size:
        pager['page_size'] = int(page_size)
    params = copy(pager)
    if kwargs:
        params.update(kwargs)
    view = api_class.as_view()
    params['format']='json'
    response = view(request,**params)
    response.render()
    return response.content,pager
示例#36
0
def api_retrieve(request, api_class, *args, **kwargs):
    flavour = django_mobile.get_flavour(request)
    page_size = 12 if flavour == 'mobile' else 24
    pager = {}
    page = request.GET.get('page', 1)
    page_size = request.GET.get(REST_FRAMEWORK['PAGINATE_BY_PARAM'], page_size)
    if page:
        pager['page'] = int(page)
    if page_size:
        pager['page_size'] = int(page_size)
    params = copy(pager)
    if kwargs:
        params.update(kwargs)
    view = api_class.as_view()
    params['format'] = 'json'
    response = view(request, **params)
    response.render()
    return response.content, pager
示例#37
0
def all_events(request):
	event_list = Event.objects.all().order_by('start_date')
	if django_mobile.get_flavour(request) == 'mobile':
		events = event_list
	else:
		paginator = Paginator(event_list, 7)

		page = request.GET.get('page')
		if not page:
			page = 1
		try:
			events = paginator.page(page)
		except PageNotAnInteger:
			# If page is not an integer, deliver first page.
			events = paginator.page(1)
		except EmptyPage:
			# If page is out of range (e.g. 9999), deliver last page of results.
			events = paginator.page(paginator.num_pages)
	return render_to_response('events.html', {"events": events}, context_instance=RequestContext(request))
示例#38
0
    def load_template(self, template_name, template_dirs=None):
        key = "{0}:{1}".format(get_flavour(), template_name)
        if template_dirs:
            # If template directories were specified, use a hash to differentiate
            key = '-'.join([template_name, sha_constructor('|'.join(template_dirs)).hexdigest()])

        if key not in self.template_cache:
            template, origin = self.find_template(template_name, template_dirs)
            if not hasattr(template, 'render'):
                try:
                    template = get_template_from_string(template, origin, template_name)
                except TemplateDoesNotExist:
                    # If compiling the template we found raises TemplateDoesNotExist,
                    # back off to returning the source and display name for the template
                    # we were asked to load. This allows for correct identification (later)
                    # of the actual template that does not exist.
                    return template, origin
            self.template_cache[key] = template
        return self.template_cache[key], None
示例#39
0
    def load_template(self, template_name, template_dirs=None):
        key = "{0}:{1}".format(get_flavour(), template_name)
        if template_dirs:
            # If template directories were specified, use a hash to differentiate
            key = '-'.join([
                template_name,
                hashlib.sha1('|'.join(template_dirs)).hexdigest()])

        if key not in self.template_cache:
            template, origin = self.find_template(template_name, template_dirs)
            if not hasattr(template, 'render'):
                try:
                    template = get_template_from_string(template, origin, template_name)
                except TemplateDoesNotExist:
                    # If compiling the template we found raises TemplateDoesNotExist,
                    # back off to returning the source and display name for
                    # the template we were asked to load. This allows for
                    # correct identification (later) of the actual template
                    # that does not exist.
                    return template, origin
            self.template_cache[key] = template
        return self.template_cache[key], None
示例#40
0
def is_mobile(request):
    return {
        'is_mobile': get_flavour() == DEFAULT_MOBILE_FLAVOUR,
    }
示例#41
0
 def cache_key(self, template_name, skip):
     """Add flavour to the cache-key."""
     result = super().cache_key(template_name, skip)
     return "{0}:{1}".format(get_flavour(), result)
示例#42
0
 def test_set_flavour(self):
     set_flavour('full')
     self.assertEqual(get_flavour(), 'full')
     set_flavour('mobile')
     self.assertEqual(get_flavour(), 'mobile')
     self.assertRaises(ValueError, set_flavour, 'spam')
示例#43
0
 def test_set_flavour(self):
     set_flavour('full')
     self.assertEqual(get_flavour(), 'full')
     set_flavour('mobile')
     self.assertEqual(get_flavour(), 'mobile')
     self.assertRaises(ValueError, set_flavour, 'spam')
示例#44
0
文件: search.py 项目: bung87/moto-moe
 def post(self, request, *args, **kwargs):
     flavour = django_mobile.get_flavour(request)
     self.results_per_page = 12 if flavour == 'mobile' else 24
     return self.list(request, *args, **kwargs)
示例#45
0
def is_mobile(request):
    return django_mobile.get_flavour(request) == "mobile"
示例#46
0
 def prepare_template_name(self, template_name):
     template_name = u'%s/%s' % (get_flavour(), template_name)
     if settings.FLAVOURS_TEMPLATE_PREFIX:
         template_name = settings.FLAVOURS_TEMPLATE_PREFIX + template_name
     return template_name
示例#47
0
 def _prepare_template_name(self, template_name):
     """Prepare the template name taking into consideration the flavor."""
     template_name = "%s/%s" % (get_flavour(), template_name)
     if settings.FLAVOURS_TEMPLATE_PREFIX:
         template_name = settings.FLAVOURS_TEMPLATE_PREFIX + template_name
     return template_name
示例#48
0
 def test_set_flavour(self):
     set_flavour("full")
     self.assertEqual(get_flavour(), "full")
     set_flavour("mobile")
     self.assertEqual(get_flavour(), "mobile")
     self.assertRaises(ValueError, set_flavour, "spam")
示例#49
0
def create(request, day_pk):
    '''
    Creates a new set. This view handles both the set form and the corresponding
    settings formsets
    '''
    day = get_object_or_404(Day, pk=day_pk)
    if day.get_owner_object().user != request.user:
        return HttpResponseForbidden()

    # Select the correct form depending on the flavour of the request.
    # The difference is that the mobile form doesn't use the autocompleter for
    # exercises, but 2 dropdowns, one to filter by category and one to select
    # the exercises themselves.
    if get_flavour(request, 'full') == 'mobile':
        form_class = SetFormMobile
    else:
        form_class = SetForm

    context = {}
    formsets = []
    form = form_class(initial={'sets': Set.DEFAULT_SETS})

    # For the mobile dropdown list we need to manually filter the exercises
    # by language and status
    if get_flavour(request, 'full') == 'mobile':
        languages = load_item_languages(LanguageConfig.SHOW_ITEM_EXERCISES)
        form.fields['exercise_list'].queryset = Exercise.objects.accepted() \
                                                        .filter(language__in=languages)

    # If the form and all formsets validate, save them
    if request.method == "POST":
        form = form_class(request.POST)
        if form.is_valid():
            for exercise in form.cleaned_data['exercises']:
                formset = SettingFormset(request.POST,
                                         queryset=Setting.objects.none(),
                                         prefix='exercise{0}'.format(
                                             exercise.id))
                formsets.append({'exercise': exercise, 'formset': formset})
        all_valid = True

        for formset in formsets:
            if not formset['formset'].is_valid():
                all_valid = False

        if form.is_valid() and all_valid:
            # Manually take care of the order, TODO: better move this to the model
            max_order = day.set_set.select_related().aggregate(
                models.Max('order'))
            form.instance.order = (max_order['order__max'] or 0) + 1
            form.instance.exerciseday = day
            set_obj = form.save()

            for formset in formsets:
                instances = formset['formset'].save(commit=False)
                for instance in instances:
                    instance.set = set_obj
                    instance.order = 1
                    instance.exercise = formset['exercise']
                    instance.save()

            return HttpResponseRedirect(
                reverse('manager:workout:view',
                        kwargs={'pk': day.get_owner_object().id}))
        else:
            logger.debug(form.errors)

    # Other context we need
    context['form'] = form
    context['day'] = day
    context['max_sets'] = Set.MAX_SETS
    context['formsets'] = formsets
    context['form_action'] = reverse('manager:set:add',
                                     kwargs={'day_pk': day_pk})
    context['extend_template'] = 'base_empty.html' if request.is_ajax(
    ) else 'base.html'
    return render(request, 'set/add.html', context)
示例#50
0
 def prepare_template_name(self, template_name):
     return self._prepare_template_name(template_name, get_flavour())
示例#51
0
def is_mobile_ajax(request):
    result = False   
    if request.is_ajax() and django_mobile.get_flavour(request) == 'mobile':
        result = True        
    
    return result
示例#52
0
 def get(self, request, *args, **kwargs):
     self.flavour = django_mobile.get_flavour(request)
     return Response(self.list())
示例#53
0
 def process_request(self, request):
     _set_request_header(request, get_flavour(request))
示例#54
0
def flavour(request):
    return {
        'flavour': get_flavour(),
    }
示例#55
0
 def process_request(self, request):
     if get_flavour(request) == 'amp':
         from django.core.urlresolvers import resolve
         current_url = resolve(request.path_info).url_name
         if current_url != 'article_detail':
             set_flavour('mobile', request, permanent=True)
示例#56
0
 def get(self, request, *args, **kwargs):
     self.flavour = django_mobile.get_flavour(request)
     return Response(self.list())