当前位置: 首页>>代码示例>>Python>>正文


Python response.TemplateResponse类代码示例

本文整理汇总了Python中django.template.response.TemplateResponse的典型用法代码示例。如果您正苦于以下问题:Python TemplateResponse类的具体用法?Python TemplateResponse怎么用?Python TemplateResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了TemplateResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: post

    def post(self, *args, **kwargs):
        # Get the chosen options ids.
        post = self.request.POST.copy()
        try:
            del post["csrfmiddlewaretoken"]
        except KeyError:
            pass
        choice_ids = map(lambda v: int(v), post.values())

        # Create a new answer and add the voter and the choices.
        voter = get_voter(self.request)
        answer = Answer.objects.create(
            gallup_id=self.kwargs["gallup_id"],
            voter=voter,
            client_identifier=get_client_identifier(self.request)
        )
        choices = Option.objects.filter(pk__in=choice_ids).all()
        answer.choices.add(*choices)

        context = self.get_context_data()
        context["show_results"] = True
        context["disabled"] = True
        context["answered_options"] = choices
        response = TemplateResponse(self.request, self.template_name, context)
        response.set_cookie(Voter.VOTER_COOKIE, voter.voter_id)
        return response
开发者ID:finnishnetsolutions,项目名称:nuortenideat,代码行数:26,代码来源:views.py

示例2: index

def index(request):
	print " "
	print "*******VIEWS INDEX******"
	print " "
	response = TemplateResponse(request, 'index.html', {} )
	response.render()
	return response
开发者ID:marcelarosalesj,项目名称:Web,代码行数:7,代码来源:views.py

示例3: verify_attendances

def verify_attendances(request):

    if 'attendance' in request.POST:
        for member in request.POST.getlist('attendance'):
            """attendance = Attendance.objects.get(pk=request.POST.get('attendance'))"""
            attendance = Attendance.objects.get(pk=member)
            attendance.verified = True
            attendance.save()

    if 'delete' in request.POST:
        for member in request.POST.getlist('delete'):
            attendance = Attendance.objects.get(pk=member)
            attendance.delete()

    order_by = request.GET.get('order_by', 'user')
    own_guild = request.user.userprofile.guild
    general_guild = Guild.objects.filter(id = general_id)

    if own_guild.abbreviation != 'TF':
        guild_users = User.objects.filter(userprofile__guild = own_guild)
    else:
        guild_users = User.objects.filter(userprofile__is_tf = True)

    unverified = Attendance.objects.filter(Q(user__in = guild_users) 
                                            & (Q(event__guild = own_guild) | Q(event__guild = general_guild))
                                            & Q(verified = False)).order_by(order_by)
    verified = Attendance.objects.filter(Q(user__in = guild_users) 
                                            & (Q(event__guild = own_guild) | Q(event__guild = general_guild))
                                            & Q(verified = True)).order_by(order_by)

    response = TemplateResponse(request, 'admin_attendances.html', {'unverified': unverified, 'verified': verified})
    response.render()
    return response
开发者ID:Jonneitapuro,项目名称:isoskaba2,代码行数:33,代码来源:views.py

示例4: home

def home(request):
    html = "appointment.home"
    t = TemplateResponse(request, "base.html", {})
    t.template_name = "index.html"
    t.render()
    # return HttpResponse(html)
    return t
开发者ID:clinicli,项目名称:webapp,代码行数:7,代码来源:views.py

示例5: show_pad

def show_pad(request, group_name, pad_name):
    # test if user is in group
    if not request.user.groups.filter(name=group_name).exists():
        return TemplateResponse(request, 'etherpad/forbidden.html', {
            'group_name': group_name,
        }, status=403)

    ep = Etherpad()
    try:
        ep.create_session(request.user, group_name)
        group_id = ep.get_group_id(group_name)
        pad_url = '{0}/p/{1}${2}'.format(
                settings.ETHERPAD_URL,
                group_id,
                pad_name)
        cookie = ep.get_session_cookie(request.user)
    except URLError:
        return TemplateResponse(request, 'etherpad/server_error.html', {
            }, status=500)

    is_fullscreen = 'fullscreen' in request.GET
    response = TemplateResponse(request, 'etherpad/pad.html', {
        'pad_url': pad_url,
        'group_name': group_name,
        'pad_name': pad_name,
        'fullscreen': is_fullscreen,
        'base_template': 'base_raw.html' if is_fullscreen else 'base.html'
    })
    cookie_domain = '.' + request.get_host()
    response.set_cookie('sessionID', cookie, domain=cookie_domain)
    response['Access-Control-Allow-Origin'] = "https://ep.mafiasi.de"
    return response
开发者ID:Nilix007,项目名称:mafiasi,代码行数:32,代码来源:views.py

示例6: test_pickling

    def test_pickling(self):
        # Create a template response. The context is
        # known to be unpickleable (e.g., a function).
        response = TemplateResponse(self.factory.get('/'),
            'first/test.html', {
                'value': 123,
                'fn': datetime.now,
            })
        self.assertRaises(ContentNotRenderedError,
                          pickle.dumps, response)

        # But if we render the response, we can pickle it.
        response.render()
        pickled_response = pickle.dumps(response)
        unpickled_response = pickle.loads(pickled_response)

        self.assertEquals(unpickled_response.content, response.content)
        self.assertEquals(unpickled_response['content-type'], response['content-type'])
        self.assertEquals(unpickled_response.status_code, response.status_code)

        # ...and the unpickled reponse doesn't have the
        # template-related attributes, so it can't be re-rendered
        self.assertFalse(hasattr(unpickled_response, '_request'))
        self.assertFalse(hasattr(unpickled_response, 'template_name'))
        self.assertFalse(hasattr(unpickled_response, 'context_data'))
        self.assertFalse(hasattr(unpickled_response, '_post_render_callbacks'))
开发者ID:MyaThandarKyaw,项目名称:django,代码行数:26,代码来源:response.py

示例7: test_pickling

    def test_pickling(self):
        # Create a template response. The context is
        # known to be unpicklable (e.g., a function).
        response = TemplateResponse(self.factory.get('/'),
            'first/test.html', {
                'value': 123,
                'fn': datetime.now,
            }
        )
        self.assertRaises(ContentNotRenderedError,
                          pickle.dumps, response)

        # But if we render the response, we can pickle it.
        response.render()
        pickled_response = pickle.dumps(response)
        unpickled_response = pickle.loads(pickled_response)

        self.assertEqual(unpickled_response.content, response.content)
        self.assertEqual(unpickled_response['content-type'], response['content-type'])
        self.assertEqual(unpickled_response.status_code, response.status_code)

        # ...and the unpickled response doesn't have the
        # template-related attributes, so it can't be re-rendered
        template_attrs = ('template_name', 'context_data',
            '_post_render_callbacks', '_request', '_current_app')
        for attr in template_attrs:
            self.assertFalse(hasattr(unpickled_response, attr))

        # ...and requesting any of those attributes raises an exception
        for attr in template_attrs:
            with self.assertRaises(AttributeError):
                getattr(unpickled_response, attr)
开发者ID:pexip,项目名称:os-python-django,代码行数:32,代码来源:test_response.py

示例8: news

def news(request):
    try:
        if request.POST.get("date_filter"):
            date_filter = int(request.POST.get("date_filter"))
        else:
            date_filter = 10
        last_date = timezone.now()-timedelta(days=date_filter)
        
        if request.user.is_anonymous():
            news = [n for n in News.objects.order_by("-date")
                    if (n.collection!=None and n.collection.public_access) # user news (public collection)
                    and (n.date>=last_date)]
        else:
            news = [n for n in News.objects.order_by("-date")
                    if ((n.collection==None and n.group==None) # general news
                    or  (n.collection!=None and n.collection.public_access) # user news (public collection)
                    or  (n.collection!=None and n.collection in request.user.get_all_permissible_collections()) # user news (collection)
                    or  (n.group!=None and n.group in request.user.groups.all())) # user news (group)
                    and (n.date>=last_date)]
    except Collection.DoesNotExist:
        raise Http404
    t = TemplateResponse(request, 'log/news.html',
                         {'news': news,
                          'date_filter': date_filter})
    return HttpResponse(t.render())
开发者ID:lauflabor-tud,项目名称:chiara-v2,代码行数:25,代码来源:views.py

示例9: logout

def logout(request):
    auth = request.COOKIES.get('auth')
    resp = logout_exp_api(auth)
    context = {'response': resp}
    response = TemplateResponse(request,'logout.html', context)
    response.delete_cookie('auth')
    return response
开发者ID:bjs9yv,项目名称:CS4501,代码行数:7,代码来源:views.py

示例10: view_cart

def view_cart(request):
    if 'cart_id' in request.COOKIES:
        cart_id = request.COOKIES["cart_id"]
        cart, created = Cart.objects.get_or_create(id=cart_id)
    else:
        if request.user.is_authenticated():
            cart, object = Cart.objects.get_or_create(user=request.user)
        else:
            cart = Cart.objects.create(user=None)

    if request.is_ajax():
        ret_dict = {}
        ret_dict['success'] = True
        ret_dict['item_type_count'] = cart.cart_products.all().count()

        from shopcart.serializer import serializer
        # serialized_cart = serializer(cart,datetime_format='string',output_type='dict',many=True)

        # 先不返回购物车中商品信息
        serialized_cart = serializer(cart, datetime_format='string', output_type='dict', many=False)
        # logger.debug(serialized_cart)
        ret_dict['cart'] = serialized_cart
        return JsonResponse(ret_dict)

    else:
        ctx = {}
        ctx['system_para'] = get_system_parameters()
        ctx['menu_products'] = get_menu_products()
        ctx['page_name'] = 'My Cart'
        if request.method == 'GET':
            ctx['cart'] = cart
            response = TemplateResponse(request, System_Config.get_template_name() + '/cart_detail.html', ctx)
            response.set_cookie('cart_id', cart.id, max_age=3600 * 24 * 365)
            return response
开发者ID:icetusorg,项目名称:cetusshop,代码行数:34,代码来源:cart.py

示例11: test_pickling

    def test_pickling(self):
        # Create a template response. The context is
        # known to be unpicklable (e.g., a function).
        response = TemplateResponse(self.factory.get("/"), "first/test.html", {"value": 123, "fn": datetime.now})
        self.assertRaises(ContentNotRenderedError, pickle.dumps, response)

        # But if we render the response, we can pickle it.
        response.render()
        pickled_response = pickle.dumps(response)
        unpickled_response = pickle.loads(pickled_response)

        self.assertEqual(unpickled_response.content, response.content)
        self.assertEqual(unpickled_response["content-type"], response["content-type"])
        self.assertEqual(unpickled_response.status_code, response.status_code)

        # ...and the unpickled response doesn't have the
        # template-related attributes, so it can't be re-rendered
        template_attrs = ("template_name", "context_data", "_post_render_callbacks", "_request")
        for attr in template_attrs:
            self.assertFalse(hasattr(unpickled_response, attr))

        # ...and requesting any of those attributes raises an exception
        for attr in template_attrs:
            with self.assertRaises(AttributeError):
                getattr(unpickled_response, attr)
开发者ID:yogidtu,项目名称:django,代码行数:25,代码来源:test_response.py

示例12: render_article

def render_article(request, article, current_language, slug):
    """
    Renders an article
    """
    context = {}
    context['article'] = article
    context['lang'] = current_language
    context['current_article'] = article
    context['has_change_permissions'] = article.has_change_permission(request)

    response = TemplateResponse(request, article.template, context)
    response.add_post_render_callback(set_page_cache)

    # Add headers for X Frame Options - this really should be changed upon moving to class based views
    xframe_options = article.tree.get_xframe_options()
    # xframe_options can be None if there's no xframe information on the page
    # (eg. a top-level page which has xframe options set to "inherit")
    if xframe_options == Page.X_FRAME_OPTIONS_INHERIT or xframe_options is None:
        # This is when we defer to django's own clickjacking handling
        return response

    # We want to prevent django setting this in their middlewear
    response.xframe_options_exempt = True

    if xframe_options == Page.X_FRAME_OPTIONS_ALLOW:
        # Do nothing, allowed is no header.
        return response
    elif xframe_options == Page.X_FRAME_OPTIONS_SAMEORIGIN:
        response['X-Frame-Options'] = 'SAMEORIGIN'
    elif xframe_options == Page.X_FRAME_OPTIONS_DENY:
        response['X-Frame-Options'] = 'DENY'
    return response
开发者ID:misli,项目名称:django-cms-articles,代码行数:32,代码来源:article_rendering.py

示例13: mount_owncloud

def mount_owncloud(request):
    # If the request is a http post
    if request.method == 'POST' and 'operation' not in request.POST:
        form = OwncloudForm(request.POST)

        if form.is_valid():
            # Mount ownCloud
            is_mounted = WebFolder.mount_owncloud(request.user, request.POST["user"], request.POST["password"])
            if is_mounted:
                message = "Your ownCloud directory was successfully mounted."
                t = TemplateResponse(request, 'info.html', 
                             {'message': message})
            else:
                message = "Mounting your ownCloud directory failed. Please try again!"
                t = TemplateResponse(request, 'error.html',
                             {'message': message})
            return HttpResponse(t.render())
        else:
            # The supplied form contained errors - just print them to the terminal.
            print form.errors
    else:
        # If the request was not a POST, display the form to enter details.
        form = OwncloudForm()
    
    t = TemplateResponse(request, 'collection/mount_owncloud.html', {'form': form})
    return HttpResponse(t.render())
开发者ID:lauflabor-tud,项目名称:chiara-v2,代码行数:26,代码来源:views.py

示例14: productEdit

def productEdit(request, id):
    if not request.user.is_active or not request.user.is_superuser:
        raise Http404 #filter other users
    try:
        id = int(id)
        product = models.Products.objects.get(id=id)
    except:
        raise Http404 #bad id or product with this id is not exist

    form = None

    if request.method == 'POST':
        response = {}
        saved    = False
        form = forms.ProductForm(request.POST, request.FILES, instance=product)
        #check form
        if form.is_valid():
            form.save()
            response['status'] = 'ok'
            saved = True
        else:
            response['status'] = 'error'

        context = RequestContext(request, { 'product':product, 'form':form, 'saved':saved })
        response['form'] = template.loader.get_template('form.html').render(context)
        response['name'] = product.name
        resp = TemplateResponse(request, '')
        resp.content = json.dumps(response)
        return resp
        #return HttpResponse(json.dumps(response))

    if request.method == 'GET':
        #create form
        form = forms.ProductForm(instance=product)
        return TemplateResponse(request, 'edit.html', {"form": form, 'product': product})
开发者ID:shevayura,项目名称:pydjtest,代码行数:35,代码来源:views.py

示例15: html_response

def html_response(request, response, content):
    """Return a html layout with sort options as the response content."""
    template = TemplateResponse(request, "profile_stats.html",
                                {"stats": content,
                                 "order_by": request.GET.get('profile', None)})
    template.render()
    return template
开发者ID:yitzc,项目名称:yet-another-django-profiler,代码行数:7,代码来源:middleware.py


注:本文中的django.template.response.TemplateResponse类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。