本文整理汇总了Python中mezzanine.utils.views.render函数的典型用法代码示例。如果您正苦于以下问题:Python render函数的具体用法?Python render怎么用?Python render使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了render函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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})
示例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)
示例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)
示例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})
示例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)
示例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)
示例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})
示例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)
示例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})
示例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)
示例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)
示例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)
示例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)
示例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)