• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python views.render函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: blog_homepage

def blog_homepage(request):
    """ 
    Display the homepage
    """
    current_site = get_current_site(request).domain

#    if current_site == "gracebreedlove.com": 
#        page = get_object_or_404(Page, slug="grace-breedlove-photography")
#        content = mark_safe(page.richtextpage.content)
#        context = { 'page' : page, 'content' : content  }
#        return render(request, "photo_index.html", context)

    if current_site == "solarpoweredyogi.com":
        settings.use_editable()
        blog_posts = BlogPost.objects.published(for_user=request.user)

        slider_posts = blog_posts[:4]
        section_posts = blog_posts[0:15]

        context = { "slider_posts" : slider_posts, "section_posts": section_posts }

        return render(request, "index.html", context)

    settings.use_editable()
    blog_posts = BlogPost.objects.published(for_user=request.user)

    slider_posts = blog_posts[:4]
    section_posts = blog_posts[0:15]

    context = { "slider_posts" : slider_posts, "section_posts": section_posts }

    return render(request, "index.html", context)
开发者ID:numon,项目名称:graces-site,代码行数:32,代码来源:views.py


示例2: frontpage

def frontpage(request):
    # @TODO: Use weight and featured fields, which need to be implemented.
    articles = Article.objects.filter(public=True).order_by('-updated_at')[:5]
    articles = paginate(articles, request.GET.get("page", 1),
                        settings.BLOG_POST_PER_PAGE,
                        settings.MAX_PAGING_LINKS)
    return render(request, ['frontpage.html'], {'articles': articles})
开发者ID:bericht,项目名称:bericht,代码行数:7,代码来源:views.py


示例3: cart

def cart(request, template="shop/cart.html"):
    """
    Display cart and handle removing items from the cart.
    """
    cart_formset = CartItemFormSet(instance=request.cart)
    discount_form = DiscountForm(request, request.POST or None)
    if request.method == "POST":
        valid = True
        if request.POST.get("update_cart"):
            valid = request.cart.has_items()
            if not valid:
                # Session timed out.
                info(request, _("Your cart has expired"))
            else:
                cart_formset = CartItemFormSet(request.POST,
                                               instance=request.cart)
                valid = cart_formset.is_valid()
                if valid:
                    cart_formset.save()
                    recalculate_discount(request)
                    info(request, _("Cart updated"))
        else:
            valid = discount_form.is_valid()
            if valid:
                discount_form.set_discount()
        if valid:
            return redirect("shop_cart")
    context = {"cart_formset": cart_formset}
    settings.use_editable()
    if (settings.SHOP_DISCOUNT_FIELD_IN_CART and
        DiscountCode.objects.active().count() > 0):
        context["discount_form"] = discount_form
    return render(request, template, context)
开发者ID:lolsborn,项目名称:cartridge,代码行数:33,代码来源:views.py


示例4: login

def login(request, template="accounts/account_login.html"):
    """
    Login form.
    """
    isAjax = False
    form = LoginForm(request.POST or None)
    next = get_login_redirect_url(request)
    if request.method == "POST" and form.is_valid():
        authenticated_user = form.save()
        #info(request, _("Successfully logged in"))
        auth_login(request, authenticated_user)
        if request.is_ajax():
            if  request.user.is_authenticated():
                return HttpResponse(simplejson.dumps(dict(url=next,
                                                          success=True)))
            else:
                return HttpResponse(simplejson.dumps(dict(success=False)))                
        else:
            return login_redirect(request)
    elif form.errors:
        return HttpResponse(simplejson.dumps(dict(errors=form.errors, success=False)))

    if request.is_ajax():
        template = "accounts/ajax_account_login.html"

    context = {"form": form, "title": _("Log in"), "next":next}
    return render(request, template, context)
开发者ID:saumishr,项目名称:mezzanine,代码行数:27,代码来源:views.py


示例5: wiki_page_revert

def wiki_page_revert(request, slug, revision_pk):
    slug_original = slug
    slug = urlize_title(slug)
    if slug != slug_original:
        return HttpResponseRedirect(
            reverse('wiki_page_revert', args=[slug, revision_pk])
        )
    try:
        wiki_pages = WikiPage.objects.published(for_user=request.user)
        wiki_page = wiki_pages.get(slug=slug)
    except WikiPage.DoesNotExist:
        return HttpResponseRedirect(reverse('wiki_page_edit', args=[slug]))
    src_revision = get_object_or_404(WikiPageRevision, page=wiki_page, pk=revision_pk)
    new_revision = WikiPageRevision(page=wiki_page,
            user=request.user if request.user.is_authenticated() else User.objects.get(id=-1))
    if request.method == 'POST':
        form = WikiPageForm(data=request.POST or None, instance=wiki_page)
        if form.is_valid():
            form.save()
            new_revision.content = form.cleaned_data["content"]
            new_revision.description = form.cleaned_data["summary"]
            new_revision.save()
            return HttpResponseRedirect(reverse('wiki_page_detail', kwargs={'slug': slug}))
    else:
        if src_revision.user:
            description = _("Reverted to revision of %(time)s by %(user)s.") % \
                    {'time': src_revision.created, 'user': src_revision.user.username}
        else:
            description = _("Reverted to anonymous revision of %(time)s.") % \
                    {'time': src_revision.created}
        form = WikiPageForm(data=request.POST or None, instance=wiki_page,
                initial={'content': src_revision.content, 'summary': description})
    return render(request, 'mezawiki/wiki_page_edit.html',
                  {'wiki_page': wiki_page, 'form': form, 'src_revision': src_revision})
开发者ID:aaronkyle,项目名称:mezzanine-wiki,代码行数:34,代码来源:views.py


示例6: wiki_page_revision

def wiki_page_revision(request, slug, rev_id,
                     template="mezawiki/wiki_page_revision.html"):
    """
    Displays a wiki page revision.
    Redirects to the edit view if the page doesn't exist.

    Custom templates are checked for using the name
    ``mezawiki/wiki_page_detail_XXX.html``
    where ``XXX`` is the wiki pages's slug.
    """
    slug_original = slug
    slug = urlize_title(slug)
    if slug != slug_original:
        return HttpResponseRedirect(
            reverse('wiki_page_revision', args=[slug])
        )
    try:
        wiki_pages = WikiPage.objects.published(for_user=request.user)
        wiki_page = wiki_pages.get(slug=slug)
        revision = WikiPageRevision.objects.get(id=rev_id)
    except WikiPage.DoesNotExist:
        return HttpResponseRedirect(reverse('wiki_page_edit', args=[slug]))
    if not wiki_page.can_view_wikipage(request.user):
        return HttpResponseForbidden(
            _("You don't have permission to view this wiki page revision."))
    context = {"wiki_page": wiki_page, "revision": revision}
    templates = [u"mezawiki/wiki_page_detail_%s.html" % unicode(slug), template]
    return render(request, templates, context)
开发者ID:aaronkyle,项目名称:mezzanine-wiki,代码行数:28,代码来源:views.py


示例7: cart_item_view

def cart_item_view(request, template="shop/product.html", form_class=AddProductForm, extra_content=None, cart_id="", item_id=""):
    cart = Cart.objects.filter(id=cart_id).first()
    item = next(item for item in cart.items.iterator() if item.id == int(item_id))
    published_products = Product.objects.published(for_user=request.user)
    product = get_object_or_404(published_products, slug=item.url.split('/')[-1])
    fields = [f.name for f in ProductVariation.option_fields()]
    variations = product.variations.all()
    variations_json = dumps([dict([(f, getattr(v, f))
        for f in fields + ["sku", "image_id"]]) for v in variations])
    variation = ProductVariation.objects.filter(sku=item.sku).first()
    v_json = dict([(f, getattr(variation, f))
        for f in fields + ["sku", "image_id"] if getattr(variation, f) is not None])
    initial_data = dict(quantity=item.quantity, **v_json)
    initial_data['embroidery_type'] = item.personalization.embroidery_type
    initial_data['value'] = item.personalization.value
    
    add_product_form = form_class(request.POST or None, product=product,
                                  initial=initial_data, to_cart=False)
    context = {
        "product": product,
        "editable_obj": product,
        "images": product.images.all(),
        "variations": variations,
        "variations_json": variations_json,
        "has_available_variations": any([v.has_price() for v in variations]),
        "add_product_form": add_product_form,
        "item": item
    }
    return render(request, template, context)
开发者ID:tresbailey,项目名称:Carolina-Belle,代码行数:29,代码来源:views.py


示例8: link_dump_tag_list

def link_dump_tag_list(request, keyword_slug,
                       template="linkdump/tag_list.html"):
    """Display a list of links for a specific Keyword."""
    keyword = get_object_or_404(Keyword, slug=keyword_slug)
    dumps = Dump.objects.filter(tags_string__contains=keyword.title).order_by(
        '-views')
    return render(request, template, {'keyword': keyword, 'dumps': dumps})
开发者ID:mattoc,项目名称:mezzanine-linkdump,代码行数:7,代码来源:views.py


示例9: account

def account(request, template="account.html"):
    """
    Display and handle both the login and signup forms.
    """
    login_form = LoginForm(request)
    signup_form = SignupForm(request)
    if request.method == "POST":
        posted_form = None
        message = ""
        if request.POST.get("login") is not None:
            login_form = LoginForm(request, request.POST)
            if login_form.is_valid():
                posted_form = login_form
                message = _("Successfully logged in")
        else:
            signup_form = SignupForm(request, request.POST)
            if signup_form.is_valid():
                new_user = signup_form.save()
                if not new_user.is_active:
                    send_verification_mail(request, new_user)
                    info(request, _("A verification email has been sent with " "a link for activating your account."))
                else:
                    posted_form = signup_form
                    message = _("Successfully signed up")
        if posted_form is not None:
            posted_form.login(request)
            info(request, message)
            return redirect(request.GET.get("next", "/"))
    context = {"login_form": login_form, "signup_form": signup_form}
    return render(request, template, context)
开发者ID:NeoChronos,项目名称:mezzanine,代码行数:30,代码来源:views.py


示例10: article_list

def article_list(request, public=None):
    api_endpoint = '/api/articles/?'
    if public:
        api_endpoint += "public=%s&" % public

    return render(request, ['article_list.html'],
                  {'api_endpoint': api_endpoint})
开发者ID:bericht,项目名称:bericht,代码行数:7,代码来源:views.py


示例11: page

def page(request, slug, template="pages/page.html", extra_context=None):
    """
    Select a template for a page and render it. The ``extra_context``
    arg will include a ``page`` object that's added via
    ``mezzanine.pages.middleware.PageMiddleware``. The page is loaded
    via the middleware so that other apps with urlpatterns that match
    the current page can include a page in their template context.
    The urlpattern that maps to this view is a catch-all pattern, in
    which case the page instance will be None, so raise a 404 then.
    """
    page_middleware = "mezzanine.pages.middleware.PageMiddleware"
    if page_middleware not in settings.MIDDLEWARE_CLASSES:
        raise ImproperlyConfigured(page_middleware + " is missing from " +
                                   "settings.MIDDLEWARE_CLASSES")

    extra_context = extra_context or {}
    try:
        page = extra_context["page"]
    except KeyError:
        raise Http404
    # Check for a template name matching the page's slug. If the homepage
    # is configured as a page instance, the template "pages/index.html" is
    # used, since the slug "/" won't match a template name.
    template_name = unicode(slug) if slug != "/" else "index"
    templates = [u"pages/%s.html" % template_name]
    # Check for a template matching the page's content model.
    if page.content_model is not None:
        templates.append(u"pages/%s.html" % page.content_model)
    templates.append(template)
    return render(request, templates, extra_context)
开发者ID:CreunaAB,项目名称:mezzanine,代码行数:30,代码来源:views.py


示例12: wiki_page_edit

def wiki_page_edit(request, slug, template="mezawiki/wiki_page_edit.html"):
    """
    Displays the form for editing and deleting a page.

    Custom templates are checked for using the name
    ``mezawiki/wiki_page_edit_XXX.html``
    where ``XXX`` is the wiki pages's slug.
    """
    try:
        wiki_pages = WikiPage.objects.published(for_user=request.user)
        wiki_page = wiki_pages.get(slug=slug)
        initial = {}
    except WikiPage.DoesNotExist:
        wiki_page = WikiPage(slug=slug)
        wiki_page.is_initial = True
        initial = {"content": _("Describe your new page %s here..." % slug)}
        #'message': _('Initial revision')}

    if request.method == "POST":
        form = WikiPageForm(request.POST, instance=wiki_page)
        if form.is_valid():
            page = form.save(commit=False)
            page.user = request.user
            page.title = slug
            page.save()
            return HttpResponseRedirect(reverse("wiki_page_detail", args=[slug]))
    else:
        form = WikiPageForm(initial=initial, instance=wiki_page)

    context = {"wiki_page": wiki_page, "form": form}
    templates = [u"mezawiki/wiki_page_edit_%s.html" % unicode(slug), template]
    return render(request, templates, context)
开发者ID:pmains,项目名称:mezzanine-wiki,代码行数:32,代码来源:views.py


示例13: page

def page(request, slug, template="pages/page.html", extra_context=None):
    """
    Display content for a page. First check for any matching page processors
    and handle them. Secondly, build the list of template names to choose
    from given the slug and type of page being viewed.
    """
    page = get_object_or_404(Page.objects.published(request.user), slug=slug)
    if page.login_required and not request.user.is_authenticated():
        path = urlquote(request.get_full_path())
        url = "%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME, path)
        return redirect(url)
    context = {"page": page}
    if extra_context is not None:
        context.update(extra_context)
    model_processors = page_processors.processors[page.content_model]
    slug_processors = page_processors.processors["slug:%s" % page.slug]
    for processor in model_processors + slug_processors:
        response = processor(request, page)
        if isinstance(response, HttpResponse):
            return response
        elif response:
            try:
                context.update(response)
            except (TypeError, ValueError):
                name = "%s.%s" % (processor.__module__, processor.__name__)
                error = ("The page processor %s returned %s but must return "
                         "HttpResponse or dict." % (name, type(response)))
                raise ValueError(error)
    templates = [u"pages/%s.html" % slug]
    if page.content_model is not None:
        templates.append(u"pages/%s.html" % page.content_model)
    templates.append(template)
    return render(request, templates, context)
开发者ID:DanHoerst,项目名称:mezzanine,代码行数:33,代码来源:views.py


示例14: account

def account(request, template="account.html"):
    """
    Display and handle both the login and signup forms.
    """
    login_form = LoginForm()
    signup_form = SignupForm()
    if request.method == "POST":
        posted_form = None
        message = ""
        if request.POST.get("login") is not None:
            login_form = LoginForm(request.POST)
            if login_form.is_valid():
                posted_form = login_form
                message = _("Successfully logged in")
        else:
            signup_form = SignupForm(request.POST)
            if signup_form.is_valid():
                signup_form.save()
                posted_form = signup_form
                message = _("Successfully signed up")
        if posted_form is not None:
            posted_form.login(request)
            info(request, message)
            return redirect(request.GET.get("next", "/"))
    context = {"login_form": login_form, "signup_form": signup_form}
    return render(request, template, context)
开发者ID:DanHoerst,项目名称:mezzanine,代码行数:26,代码来源:views.py


示例15: comment

def comment(request, template="generic/comments.html"):
    """
    Handle a ``ThreadedCommentForm`` submission and redirect back to its
    related object.
    """
    try:
        model = get_model(*request.POST["content_type"].split(".", 1))
        obj = model.objects.get(id=request.POST["object_pk"])
        if request.method != "POST":
            raise ObjectDoesNotExist()
    except (KeyError, TypeError, AttributeError, ObjectDoesNotExist):
        # Something was missing from the post so abort.
        return HttpResponseRedirect("/")
    form = ThreadedCommentForm(request, obj, request.POST or None)
    if form.is_valid():
        comment = form.get_comment_object()
        if request.user.is_authenticated():
            comment.user = request.user
        comment.by_author = request.user == getattr(obj, "user", None)
        comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR", request.META["REMOTE_ADDR"])
        comment.replied_to_id = request.POST.get("replied_to")
        comment.save()
        response = HttpResponseRedirect(comment.get_absolute_url())
        # Store commenter's details in a cookie for 90 days.
        cookie_expires = 60 * 60 * 24 * 90
        for field in ThreadedCommentForm.cookie_fields:
            cookie_name = ThreadedCommentForm.cookie_prefix + field
            cookie_value = request.POST.get(field, "")
            set_cookie(response, cookie_name, cookie_value, cookie_expires)
        return response
    else:
        # Show errors with stand-alone comment form.
        context = {"obj": obj, "posted_comment_form": form}
        return render(request, template, context)
开发者ID:Joe8Bit,项目名称:mezzanine,代码行数:34,代码来源:views.py


示例16: displayable_links_js

def displayable_links_js(request, template_name="admin/displayable_links.js"):
    """
    Renders a list of url/title pairs for all ``Displayable`` subclass
    instances into JavaScript that's used to populate a list of links
    in TinyMCE.
    """
    links = []
    if "mezzanine.pages" in settings.INSTALLED_APPS:
        from mezzanine.pages.models import Page
        is_page = lambda obj: isinstance(obj, Page)
    else:
        is_page = lambda obj: False
    # For each item's title, we use its model's verbose_name, but in the
    # case of Page subclasses, we just use "Page", and then sort the items
    # by whether they're a Page subclass or not, then by their URL.
    for url, obj in Displayable.objects.url_map(for_user=request.user).items():
        title = getattr(obj, "titles", obj.title)
        real = hasattr(obj, "id")
        page = is_page(obj)
        if real:
            verbose_name = _("Page") if page else obj._meta.verbose_name
            title = "%s: %s" % (verbose_name, title)
        links.append((not page and real, url, title))
    context = {"links": [link[1:] for link in sorted(links)]}
    content_type = "text/javascript"
    return render(request, template_name, context, content_type=content_type)
开发者ID:hari102,项目名称:SportsQuotient,代码行数:26,代码来源:views.py


示例17: invoice

def invoice(request, order_id, template="shop/order_invoice.html"):
    """
    Display a plain text invoice for the given order. The order must
    belong to the user which is checked via session or ID if
    authenticated, or if the current user is staff.
    """
    lookup = {"id": order_id}
    if not request.user.is_authenticated():
        lookup["key"] = request.session.session_key
    elif not request.user.is_staff:
        lookup["user_id"] = request.user.id
    order = get_object_or_404(Order, **lookup)
    context = {"order": order}
    context.update(order.details_as_dict())
    context = RequestContext(request, context)
    if request.GET.get("format") == "pdf":
        response = HttpResponse(mimetype="application/pdf")
        name = slugify("%s-invoice-%s" % (settings.SITE_TITLE, order.id))
        response["Content-Disposition"] = "attachment; filename=%s.pdf" % name
        html = get_template(template).render(context)
        import ho.pisa

        ho.pisa.CreatePDF(html, response)
        return response
    return render(request, template, context)
开发者ID:readevalprint,项目名称:cartridge,代码行数:25,代码来源:views.py


示例18: retail_signup

def retail_signup(request, template="accounts/retail_signup.html"):
  form = ProfileForm(request.POST or None)
  if request.method == "POST" and form.is_valid():
    new_user = form.save()

    # Add to campaign monitor
    if bool(form.cleaned_data.get("optin")):
      cm_api = CampaignMonitorApi(settings.CM_API_KEY, settings.CM_CLIENT_ID)
      listid = settings.CM_RETAIL_LIST_ID
      custom_fields = {}
      #try:
      cm_api.subscriber_add(
          listid,
          form.cleaned_data.get("email"),
          form.cleaned_data.get("first_name") + ' ' + form.cleaned_data.get("last_name"),
          custom_fields=custom_fields)
      #except:
      #  pass

    if not new_user.is_active:
      send_verification_mail(request, new_user, "signup_verify")
      info(request, "A verification email has been sent with a link for activating your account.")
    else:
      info(request, "Successfully signed up")
      auth_login(request, new_user)
      return my_login_redirect(request)
  context = {"form": form, "title": "Customer Registration"}
  return render(request, template, context)
开发者ID:zs425,项目名称:Manai-python-,代码行数:28,代码来源:views.py


示例19: user_bike_list

def user_bike_list(request, template="pages/bikeListMain.html"):
    u = User.objects.get(username=request.user.username)
    if u.bikes.count() == 0:
        messages.info(request, _("Your bikes  list is empty"))
        return HttpResponseRedirect("/bikelist/addbike/")
    context = {"bicycles": u.bikes.all(), "user_name": request.user.username}
    return render(request, template, context)
开发者ID:skyfion,项目名称:zenBikeMezzanine,代码行数:7,代码来源:views.py


示例20: contact

def contact(request, template_name = 'index.html'):
	if request.method == 'POST':
		contact_form = ContactForm(request.POST)
		if contact_form.is_valid():
			post_data = contact_form.cleaned_data
			nom = post_data.get('nom','')
			tel = post_data.get('tel','')
			from_email = post_data.get('email')
			body = post_data.get('message')
			recipient_list = list(settings.RECIPIENT_LIST)

			subject = 'HorizonPlus : Vous avez recu un email de %s' % from_email

			message = body 
			message += '<br />------------------------------------'
			message += '<br />%s (%s)' % (nom, tel)

			send_mail(subject, message, from_email, recipient_list)
			message = '<strong>votre message a bien ete envoye. Nous vous repondrons dans les plus brefs delais.</strong>'
			info(request, message, extra_tags='success')
	else:
		contact_form = ContactForm()

	context = {
		'contact_form' : contact_form,
	}

	return render(request, template_name, context)
开发者ID:webpioneer,项目名称:horizon,代码行数:28,代码来源:views.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python views.set_cookie函数代码示例发布时间:2022-05-27
下一篇:
Python views.paginate函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap