本文整理汇总了Python中modoboa.lib.webutils._render_to_string函数的典型用法代码示例。如果您正苦于以下问题:Python _render_to_string函数的具体用法?Python _render_to_string怎么用?Python _render_to_string使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_render_to_string函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: viewparameters
def viewparameters(request, tplname='core/parameters.html'):
return render_to_json_response({
"left_selection": "parameters",
"content": _render_to_string(request, tplname, {
"forms": parameters.get_admin_forms
})
})
示例2: autoreply
def autoreply(request, tplname="postfix_autoreply/autoreply.html"):
mb = Mailbox.objects.get(user=request.user.id)
try:
arm = ARmessage.objects.get(mbox=mb.id)
except ARmessage.DoesNotExist:
arm = None
if request.method == "POST":
if arm:
form = ARmessageForm(request.POST, instance=arm)
else:
form = ARmessageForm(request.POST)
if form.is_valid():
arm = form.save(commit=False)
arm.fromdate = form.cleaned_data["fromdate"]
arm.untildate = form.cleaned_data["untildate"]
arm.mbox = mb
arm.save()
return render_to_json_response(
_("Auto reply message updated successfully.")
)
return render_to_json_response(
{"form_errors": form.errors}, status=400
)
form = ARmessageForm(instance=arm)
return render_to_json_response({
"content": _render_to_string(request, tplname, {"form": form}),
"onload_cb": "autoreply_cb"
})
示例3: list_quotas
def list_quotas(request, tplname="admin/quotas.html"):
from modoboa.lib.dbutils import db_type
sort_order, sort_dir = get_sort_order(request.GET, "address")
mboxes = Mailbox.objects.get_for_admin(
request.user, request.GET.get("searchquery", None)
)
mboxes = mboxes.exclude(quota=0)
if sort_order in ["address", "quota", "quota_value__bytes"]:
mboxes = mboxes.order_by("%s%s" % (sort_dir, sort_order))
elif sort_order == "quota_usage":
if db_type() == "postgres":
select = '(admin_quota.bytes::float / (CAST(admin_mailbox.quota AS BIGINT) * 1048576)) * 100'
else:
select = 'admin_quota.bytes / (admin_mailbox.quota * 1048576) * 100'
mboxes = mboxes.extra(
select={'quota_usage': select},
where=["admin_quota.mbox_id=admin_mailbox.id"],
tables=["admin_quota"],
order_by=["%s%s" % (sort_dir, sort_order)]
)
else:
raise BadRequest(_("Invalid request"))
page = get_listing_page(mboxes, request.GET.get("page", 1))
return render_to_json_response({
"page": page.number,
"paginbar": pagination_bar(page),
"table": _render_to_string(request, tplname, {
"mboxes": page
})
})
示例4: _domains
def _domains(request):
sort_order, sort_dir = get_sort_order(request.GET, "name")
filters = dict(
(flt, request.GET.get(flt, None))
for flt in ['domfilter', 'searchquery']
+ events.raiseQueryEvent('ExtraDomainFilters')
)
request.session['domains_filters'] = filters
domainlist = get_domains(request.user, **filters)
if sort_order == 'name':
domainlist = sorted(
domainlist,
key=lambda d: getattr(d, sort_order), reverse=sort_dir == '-'
)
else:
domainlist = sorted(domainlist, key=lambda d: d.tags[0],
reverse=sort_dir == '-')
context = {
"handle_mailboxes": parameters.get_admin(
"HANDLE_MAILBOXES", raise_error=False),
"auto_account_removal": parameters.get_admin("AUTO_ACCOUNT_REMOVAL")
}
page = get_listing_page(domainlist, request.GET.get("page", 1))
if page is None:
context["length"] = 0
else:
context["rows"] = _render_to_string(
request, 'admin/domains_table.html', {
'domains': page.object_list,
}
)
context["pages"] = [page.number]
return render_to_json_response(context)
示例5: profile
def profile(request, tplname='core/user_profile.html'):
update_password = True
if True in events.raiseQueryEvent("PasswordChange", request.user):
update_password = False
if request.method == "POST":
form = ProfileForm(
update_password, request.POST, instance=request.user
)
if form.is_valid():
form.save()
if update_password and form.cleaned_data["confirmation"] != "":
request.session["password"] = encrypt(form.cleaned_data["confirmation"])
return ajax_simple_response(dict(
status="ok", respmsg=_("Profile updated")
))
return ajax_simple_response({
"status": "ko",
"errors": form.errors
})
form = ProfileForm(update_password, instance=request.user)
return ajax_simple_response({
"status": "ok",
"content": _render_to_string(request, tplname, {
"form": form
})
})
示例6: viewparameters
def viewparameters(request, tplname='admin/parameters.html'):
return ajax_simple_response({
"status": "ok",
"left_selection": "parameters",
"content": _render_to_string(request, tplname, {
"forms": parameters.get_admin_forms
})
})
示例7: send_mail
def send_mail(request, form, posturl=None):
"""Email verification and sending.
If the form does not present any error, a new MIME message is
constructed. Then, a connection is established with the defined
SMTP server and the message is finally sent.
:param request: a Request object
:param posturl: the url to post the message form to
:return: a 2-uple (True|False, HttpResponse)
"""
if not form.is_valid():
editormode = parameters.get_user(request.user, "EDITOR")
listing = _render_to_string(
request, "webmail/compose.html",
{"form": form, "noerrors": True,
"body": form.cleaned_data.get("body", "").strip(),
"posturl": posturl}
)
return False, dict(status="ko", listing=listing, editor=editormode)
msg = form.to_msg(request)
rcpts = prepare_addresses(form.cleaned_data["to"], "envelope")
for hdr in ["cc", "cci"]:
if form.cleaned_data[hdr]:
msg[hdr.capitalize()] = prepare_addresses(form.cleaned_data[hdr])
rcpts += prepare_addresses(form.cleaned_data[hdr], "envelope")
try:
secmode = parameters.get_admin("SMTP_SECURED_MODE")
if secmode == "ssl":
s = smtplib.SMTP_SSL(parameters.get_admin("SMTP_SERVER"),
int(parameters.get_admin("SMTP_PORT")))
else:
s = smtplib.SMTP(parameters.get_admin("SMTP_SERVER"),
int(parameters.get_admin("SMTP_PORT")))
if secmode == "starttls":
s.starttls()
except Exception as text:
raise WebmailInternalError(str(text))
if parameters.get_admin("SMTP_AUTHENTICATION") == "yes":
try:
s.login(request.user.username, get_password(request))
except smtplib.SMTPException as err:
raise WebmailInternalError(str(err))
try:
s.sendmail(request.user.email, rcpts, msg.as_string())
s.quit()
except smtplib.SMTPException as err:
raise WebmailInternalError(str(err))
sentfolder = parameters.get_user(request.user, "SENT_FOLDER")
get_imapconnector(request).push_mail(sentfolder, msg)
clean_attachments(request.session["compose_mail"]["attachments"])
del request.session["compose_mail"]
return True, {}
示例8: dologin
def dologin(request):
error = None
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
logger = logging.getLogger("modoboa.auth")
user = authenticate(username=form.cleaned_data["username"], password=form.cleaned_data["password"])
if user and user.is_active:
login(request, user)
if not form.cleaned_data["rememberme"]:
request.session.set_expiry(0)
if request.user.has_mailbox:
request.session["password"] = encrypt(form.cleaned_data["password"])
request.session["django_language"] = parameters.get_user(request.user, "LANG", app="general")
logger.info(_("User '%s' successfully logged in" % user.username))
events.raiseEvent("UserLogin", request, form.cleaned_data["username"], form.cleaned_data["password"])
nextlocation = request.POST.get("next", None)
if nextlocation is None or nextlocation == "None":
if user.group == "SimpleUsers":
nextlocation = reverse("modoboa.lib.webutils.topredirection")
else:
nextlocation = reverse("domains")
return HttpResponseRedirect(nextlocation)
error = _("Your username and password didn't match. Please try again.")
logger.warning(
"Failed connection attempt from '%(addr)s' as user '%(user)s'"
% {"addr": request.META["REMOTE_ADDR"], "user": form.cleaned_data["username"]}
)
nextlocation = request.POST.get("next", None)
httpcode = 401
else:
form = LoginForm()
nextlocation = request.GET.get("next", None)
httpcode = 200
return HttpResponse(
_render_to_string(
request,
"registration/login.html",
{
"form": form,
"error": error,
"next": nextlocation,
"annoucements": events.raiseQueryEvent("GetAnnouncement", "loginpage"),
},
),
status=httpcode,
)
示例9: render_mboxes_list
def render_mboxes_list(request, imapc):
"""Return the HTML representation of a mailboxes list
:param request: a ``Request`` object
:param imapc: an ``IMAPconnector` object
:return: a string
"""
curmbox = WebmailNavigationParameters(request).get("mbox", "INBOX")
return _render_to_string(
request,
"webmail/folders.html",
{"selected": curmbox, "mboxes": imapc.getmboxes(request.user), "withunseen": True},
)
示例10: graphs
def graphs(request):
gset = request.GET.get("gset", None)
gsets = events.raiseDictEvent("GetGraphSets")
if not gset in gsets:
raise NotFound(_("Unknown graphic set"))
searchq = request.GET.get("searchquery", None)
period = request.GET.get("period", "day")
tplvars = dict(graphs=[], period=period)
if searchq in [None, "global"]:
if not request.user.is_superuser:
if not Domain.objects.get_for_admin(request.user).count():
return render_to_json_response({})
tplvars.update(
domain=Domain.objects.get_for_admin(request.user)[0].name
)
else:
tplvars.update(domain="global")
else:
domain = Domain.objects.filter(name__contains=searchq)
if domain.count() != 1:
return render_to_json_response({})
if not request.user.can_access(domain[0]):
raise PermDeniedException
tplvars.update(domain=domain[0].name)
if period == "custom":
if not "start" in request.GET or not "end" in request.GET:
raise BadRequest(_("Bad custom period"))
start = request.GET["start"]
end = request.GET["end"]
G = Grapher()
expr = re.compile(r'[:\- ]')
period_name = "%s_%s" % (expr.sub('', start), expr.sub('', end))
for tpl in gsets[gset].get_graphs():
tplvars['graphs'].append(tpl.display_name)
G.process(
tplvars["domain"], period_name, str2Time(*expr.split(start)),
str2Time(*expr.split(end)), tpl
)
tplvars["period_name"] = period_name
tplvars["start"] = start
tplvars["end"] = end
else:
tplvars['graphs'] = gsets[gset].get_graph_names()
return render_to_json_response({
'content': _render_to_string(request, "stats/graphs.html", tplvars)
})
示例11: graphs
def graphs(request):
gset = request.GET.get("gset", None)
gsets = events.raiseDictEvent("GetGraphSets")
if not gset in gsets:
raise ModoboaException(_("Unknown graphic set"))
searchq = request.GET.get("searchquery", None)
period = request.GET.get("period", "day")
tplvars = dict(graphs=[], period=period)
if searchq in [None, "global"]:
if not request.user.is_superuser:
if not Domain.objects.get_for_admin(request.user).count():
return ajax_simple_response({"status": "ok"})
tplvars.update(
domain=Domain.objects.get_for_admin(request.user)[0].name
)
else:
tplvars.update(domain="global")
else:
domain = Domain.objects.filter(name__contains=searchq)
if domain.count() != 1:
return ajax_simple_response({"status": "ok"})
if not request.user.can_access(domain[0]):
raise PermDeniedException
tplvars.update(domain=domain[0].name)
if period == "custom":
if not "start" in request.GET or not "end" in request.GET:
raise ModoboaException(_("Bad custom period"))
start = request.GET["start"]
end = request.GET["end"]
G = Grapher()
period_name = "%s_%s" % (start.replace('-', ''), end.replace('-', ''))
for tpl in gsets[gset].get_graphs():
tplvars['graphs'].append(tpl.display_name)
G.process(
tplvars["domain"], period_name, str2Time(*start.split('-')),
str2Time(*end.split('-')), tpl
)
tplvars["period_name"] = period_name
tplvars["start"] = start
tplvars["end"] = end
else:
tplvars['graphs'] = gsets[gset].get_graph_names()
return ajax_simple_response(dict(
status="ok",
content=_render_to_string(request, "stats/graphs.html", tplvars)
))
示例12: calendars_page
def calendars_page(request, tplname="radicale/calendars_page.html"):
"""Return a page of calendars.
The content depends on current user's role.
"""
page = get_calendar_page(request)
if page is None:
context = {"length": 0}
else:
context = {
"rows": _render_to_string(request, tplname, {
"calendars": page.object_list,
"with_owner": request.user.group != "SimpleUsers"
}),
"page": page.number
}
return render_to_json_response(context)
示例13: viewextensions
def viewextensions(request, tplname="core/extensions.html"):
from modoboa.core.extensions import exts_pool
exts = exts_pool.list_all()
for ext in exts:
try:
dbext = Extension.objects.get(name=ext["id"])
ext["selection"] = dbext.enabled
except Extension.DoesNotExist:
dbext = Extension()
dbext.name = ext["id"]
dbext.enabled = False
dbext.save()
ext["selection"] = False
tbl = ExtensionsTable(request, exts)
return ajax_simple_response({"status": "ok", "content": _render_to_string(request, tplname, {"extensions": tbl})})
示例14: listmailbox
def listmailbox(request, defmailbox="INBOX", update_session=True):
"""Mailbox content listing.
Return a list of messages contained in the specified mailbox. The
number of elements returned depends on the ``MESSAGES_PER_PAGE``
parameter. (user preferences)
:param request: a ``Request`` object
:param defmailbox: the default mailbox (when not present inside
request arguments)
:return: a dictionnary
"""
navparams = WebmailNavigationParameters(request, defmailbox)
previous_page_id = int(navparams["page"]) if "page" in navparams else None
if update_session:
navparams.store()
mbox = navparams.get('mbox')
page_id = int(navparams["page"])
mbc = get_imapconnector(request)
mbc.parse_search_parameters(
navparams.get("criteria"), navparams.get("pattern"))
paginator = Paginator(
mbc.messages_count(folder=mbox, order=navparams.get("order")),
int(parameters.get_user(request.user, "MESSAGES_PER_PAGE"))
)
page = paginator.getpage(page_id)
content = ""
if page is not None:
email_list = mbc.fetch(page.id_start, page.id_stop, mbox)
content = _render_to_string(request, "webmail/email_list.html", {
"email_list": email_list,
"page": page_id,
"with_top_div": request.GET.get("scroll", "false") == "false"
})
length = len(content)
else:
if page_id == 1:
content = "<div class='alert alert-info'>{0}</div>".format(
_("Empty mailbox")
)
length = 0
if previous_page_id is not None:
navparams["page"] = previous_page_id
return {"listing": content, "length": length, "pages": [page_id]}
示例15: preferences
def preferences(request):
if request.method == "POST":
for formdef in parameters.get_user_forms(request.user, request.POST)():
form = formdef["form"]
if form.is_valid():
form.save()
continue
return render_to_json_response({
"prefix": form.app, "form_errors": form.errors
}, status=400)
return render_to_json_response(_("Preferences saved"))
return render_to_json_response({
"content": _render_to_string(request, "core/user_preferences.html", {
"forms": parameters.get_user_forms(request.user)
})
})