本文整理汇总了Python中misago.shortcuts.render_to_response函数的典型用法代码示例。如果您正苦于以下问题:Python render_to_response函数的具体用法?Python render_to_response怎么用?Python render_to_response使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了render_to_response函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: signature
def signature(request):
# Intercept all requests if we can't use signature
if not request.acl.usercp.can_use_signature():
return error403(request)
if request.user.signature_ban:
return render_to_response('usercp/signature_banned.html',
context_instance=RequestContext(request, {
'tab': 'signature'}));
siggy_text = ''
message = request.messages.get_message('usercp_signature')
if request.method == 'POST':
form = SignatureForm(request.POST, request=request, initial={'signature': request.user.signature})
if form.is_valid():
request.user.signature = form.cleaned_data['signature']
if request.user.signature:
request.user.signature_preparsed = signature_markdown(request.acl,
request.user.signature)
else:
request.user.signature_preparsed = None
request.user.save(force_update=True)
messages.success(request, _("Your signature has been changed."), 'usercp_signature')
return redirect(reverse('usercp_signature'))
else:
message = Message(form.non_field_errors()[0], messages.ERROR)
else:
form = SignatureForm(request=request, initial={'signature': request.user.signature})
return render_to_response('usercp/signature.html',
context_instance=RequestContext(request, {
'message': message,
'tab': 'signature',
'form': form}));
示例2: form
def form(request):
"""
Allow admins to generate fancy statistic graphs for different models
"""
models_map = {}
for model in models.get_models():
try:
getattr(model.objects, "filter_stats")
statistics_providers.append((str(model.__name__).lower(), model.statistics_name))
models_map[str(model.__name__).lower()] = model
except AttributeError:
pass
if not statistics_providers:
"""
Something went FUBAR - Misago ships with some stats providers out of box
If those providers cant be found, this means Misago filesystem is corrupted
"""
return render_to_response("stats/not_available.html", context_instance=RequestContext(request))
message = None
if request.method == "POST":
form = GenerateStatisticsForm(request.POST, provider_choices=statistics_providers, request=request)
if form.is_valid():
date_start = form.cleaned_data["date_start"]
date_end = form.cleaned_data["date_end"]
if date_start > date_end:
# Reverse dates if start is after end
date_temp = date_end
date_end = date_start
date_start = date_temp
# Assert that dates are correct
if date_end == date_start:
message = Message(_("Start and end date are same"), messages.ERROR)
elif check_dates(date_start, date_end, form.cleaned_data["stats_precision"]):
message = check_dates(date_start, date_end, form.cleaned_data["stats_precision"])
else:
messages.success(request, _("Statistical report has been created."), "admin_stats")
return redirect(
reverse(
"admin_stats_graph",
kwargs={
"model": form.cleaned_data["provider_model"],
"date_start": date_start.strftime("%Y-%m-%d"),
"date_end": date_end.strftime("%Y-%m-%d"),
"precision": form.cleaned_data["stats_precision"],
},
)
)
else:
message = Message(form.non_field_errors()[0], messages.ERROR)
else:
form = GenerateStatisticsForm(provider_choices=statistics_providers, request=request)
return render_to_response(
"stats/form.html", {"form": form, "message": message}, context_instance=RequestContext(request)
)
示例3: form
def form(request):
"""
Allow admins to generate fancy statistic graphs for different models
"""
statistics_providers = []
models_map = {}
for model in models.get_models():
try:
getattr(model.objects, 'filter_stats')
statistics_providers.append((str(model.__name__).lower(), model.statistics_name))
models_map[str(model.__name__).lower()] = model
except AttributeError:
pass
if not statistics_providers:
"""
Something went FUBAR - Misago ships with some stats providers out of box
If those providers cant be found, this means Misago filesystem is corrupted
"""
return render_to_response('stats/not_available.html',
context_instance=RequestContext(request));
message = None
if request.method == 'POST':
form = GenerateStatisticsForm(request.POST, provider_choices=statistics_providers, request=request)
if form.is_valid():
date_start = form.cleaned_data['date_start']
date_end = form.cleaned_data['date_end']
if date_start > date_end:
# Reverse dates if start is after end
date_temp = date_end
date_end = date_start
date_start = date_temp
# Assert that dates are correct
if date_end == date_start:
message = Message(_('Start and end date are same'), messages.ERROR)
elif check_dates(date_start, date_end, form.cleaned_data['stats_precision']):
message = check_dates(date_start, date_end, form.cleaned_data['stats_precision'])
else:
messages.success(request, _('Statistical report has been created.'), 'admin_stats')
return redirect(reverse('admin_stats_graph', kwargs={
'model': form.cleaned_data['provider_model'],
'date_start': date_start.strftime('%Y-%m-%d'),
'date_end': date_end.strftime('%Y-%m-%d'),
'precision': form.cleaned_data['stats_precision']
}))
else:
message = Message(form.non_field_errors()[0], messages.ERROR)
else:
form = GenerateStatisticsForm(provider_choices=statistics_providers, request=request)
return render_to_response('stats/form.html',
{
'form': form,
'message': message,
},
context_instance=RequestContext(request));
示例4: forum_map
def forum_map(request):
return render_to_response('forum_map.html',
{
'forums': Forum.objects.treelist(request.acl.forums,
Forum.objects.special_model('root'))
},
context_instance=RequestContext(request));
示例5: options
def options(request):
message = request.messages.get_message('usercp_options')
if request.method == 'POST':
form = UserForumOptionsForm(request.POST, request=request)
if form.is_valid():
request.user.hide_activity = form.cleaned_data['hide_activity']
request.user.allow_pds = form.cleaned_data['allow_pds']
request.user.receive_newsletters = form.cleaned_data['newsletters']
request.user.timezone = form.cleaned_data['timezone']
request.user.subscribe_start = form.cleaned_data['subscribe_start']
request.user.subscribe_reply = form.cleaned_data['subscribe_reply']
request.user.save(force_update=True)
messages.success(request, _("Forum options have been changed."), 'usercp_options')
return redirect(reverse('usercp'))
message = Message(form.non_field_errors()[0], messages.ERROR)
else:
form = UserForumOptionsForm(request=request, initial={
'newsletters': request.user.receive_newsletters,
'hide_activity': request.user.hide_activity,
'allow_pds': request.user.allow_pds,
'timezone': request.user.timezone,
'subscribe_start': request.user.subscribe_start,
'subscribe_reply': request.user.subscribe_reply,
})
return render_to_response('usercp/options.html',
context_instance=RequestContext(request, {
'message': message,
'tab': 'options',
'form': form}));
示例6: thread_action_move
def thread_action_move(self):
message = None
if self.request.POST.get('do') == 'move':
form = MoveThreadsForm(self.request.POST, request=self.request, forum=self.forum)
if form.is_valid():
new_forum = form.cleaned_data['new_forum']
self.thread.move_to(new_forum)
self.thread.save(force_update=True)
self.thread.set_checkpoint(self.request, 'moved', forum=self.forum)
self.forum.sync()
self.forum.save(force_update=True)
new_forum.sync()
new_forum.save(force_update=True)
messages.success(self.request, _('Thread has been moved to "%(forum)s".') % {'forum': new_forum.name}, 'threads')
return None
message = Message(form.non_field_errors()[0], messages.ERROR)
else:
form = MoveThreadsForm(request=self.request, forum=self.forum)
return render_to_response('%ss/move_thread.html' % self.type_prefix,
{
'type_prefix': self.type_prefix,
'message': message,
'forum': self.forum,
'parents': self.parents,
'thread': self.thread,
'form': form,
},
context_instance=RequestContext(self.request));
示例7: form
def form(request):
message = None
if request.method == 'POST':
form = UserSendActivationMailForm(request.POST, request=request)
if form.is_valid():
user = form.found_user
user_ban = Ban.objects.check_ban(username=user.username, email=user.email)
if user_ban:
return error_banned(request, user, user_ban)
if user.activation == User.ACTIVATION_NONE:
return redirect_message(request, messages.INFO, _("%(username)s, your account is already active.") % {'username': user.username})
if user.activation == User.ACTIVATION_ADMIN:
return redirect_message(request, messages.INFO, _("%(username)s, only board administrator can activate your account.") % {'username': user.username})
user.email_user(
request,
'users/activation/resend',
_("Account Activation"),
)
return redirect_message(request, messages.SUCCESS, _("%(username)s, e-mail containing new activation link has been sent to %(email)s.") % {'username': user.username, 'email': user.email})
else:
message = Message(form.non_field_errors()[0], messages.ERROR)
else:
form = UserSendActivationMailForm(request=request)
return render_to_response('resend_activation.html',
{
'message': message,
'form': form,
},
context_instance=RequestContext(request));
示例8: call
def call(self, **kwargs):
result = self.request.session.get('search_results')
if not result:
return error404(self.request, _("No search results were found."))
items = result['search_results']
items_total = len(items);
try:
pagination = make_pagination(kwargs.get('page', 0), items_total, 12)
except Http404:
return redirect(reverse('search_results'))
return render_to_response('search/results.html',
{
'search_in': result.get('search_in'),
'search_route': result.get('search_route'),
'search_query': result['search_query'],
'search_author': result.get('search_author'),
'search_thread_titles': result.get('search_thread_titles'),
'search_thread': result.get('search_thread'),
'results': Post.objects.filter(id__in=items).select_related('forum', 'thread', 'user').order_by('-pk')[pagination['start']:pagination['stop']],
'items_total': items_total,
'pagination': pagination,
},
context_instance=RequestContext(self.request))
示例9: posts
def posts(request, user, page=0):
queryset = user.post_set.filter(forum_id__in=Forum.objects.readable_forums(request.acl)).filter(deleted=False).filter(moderated=False)
count = queryset.count()
try:
pagination = make_pagination(page, count, 12)
except Http404:
return redirect(reverse('user_posts', kwargs={'user': user.id, 'username': user.username_slug}))
cache_key = 'user_profile_posts_graph_%s' % user.pk
graph = cache.get(cache_key, 'nada')
if graph == 'nada':
if user.posts:
graph = user.timeline(queryset.filter(date__gte=timezone.now()-timedelta(days=100)))
else:
graph = [0 for x in range(100)]
cache.set(cache_key, graph, 14400)
return render_to_response('profiles/posts.html',
context_instance=RequestContext(request, {
'profile': user,
'tab': 'posts',
'graph_max': max(graph),
'graph': (str(i) for i in graph),
'items_total': count,
'items': queryset.select_related('thread', 'forum').order_by('-id')[pagination['start']:pagination['stop']],
'pagination': pagination,
}));
示例10: dispatch
def dispatch(self, request, **kwargs):
try:
next = self.post.change_set.filter(id__gt=self.change.pk)[:1][0]
compare_to = next.post_content
except IndexError:
next = None
compare_to = self.post.post
try:
prev = self.post.change_set.filter(id__lt=self.change.pk).order_by('-id')[:1][0]
except IndexError:
prev = None
self.forum.closed = self.proxy.closed
return render_to_response('%ss/changelog_diff.html' % self.type_prefix,
self._template_vars({
'forum': self.forum,
'parents': self.parents,
'thread': self.thread,
'post': self.post,
'change': self.change,
'next': next,
'prev': prev,
'message': request.messages.get_message('changelog'),
'l': 1,
'diff': difflib.ndiff(self.change.post_content.splitlines(), compare_to.splitlines()),
}),
context_instance=RequestContext(request))
示例11: action_move
def action_move(self, ids):
threads = []
for thread in self.threads:
if thread.pk in ids:
threads.append(thread)
if self.request.POST.get('origin') == 'move_form':
form = MoveThreadsForm(self.request.POST, request=self.request, forum=self.forum)
if form.is_valid():
new_forum = form.cleaned_data['new_forum']
for thread in threads:
thread.move_to(new_forum)
thread.save(force_update=True)
thread.set_checkpoint(self.request, 'moved', forum=self.forum)
thread.update_current_dates()
new_forum.sync()
new_forum.save(force_update=True)
self.forum.sync()
self.forum.save(force_update=True)
messages.success(self.request, _('Selected threads have been moved to "%(forum)s".') % {'forum': new_forum.name}, 'threads')
return None
self.message = Message(form.non_field_errors()[0], messages.ERROR)
else:
form = MoveThreadsForm(request=self.request, forum=self.forum)
return render_to_response('%ss/move_threads.html' % self.type_prefix,
{
'type_prefix': self.type_prefix,
'search_in': self.search_in,
'message': self.message,
'forum': self.forum,
'parents': self.parents,
'threads': threads,
'form': form,
},
context_instance=RequestContext(self.request));
示例12: decorator
def decorator(*args, **kwargs):
request = args[0]
if request.user.avatar_ban:
return render_to_response('usercp/avatar_banned.html',
context_instance=RequestContext(request, {
'tab': 'avatar'}));
return f(*args, **kwargs)
示例13: crop
def crop(request, upload=False):
if upload and (not request.user.avatar_temp or not 'upload' in settings.avatars_types):
return error404(request)
if not upload and request.user.avatar_type != 'upload':
messages.error(request, _("Crop Avatar option is avaiable only when you use uploaded image as your avatar."), 'usercp_avatar')
return redirect(reverse('usercp_avatar'))
message = request.messages.get_message('usercp_avatar')
if request.method == 'POST':
if request.csrf.request_secure(request):
try:
image_path = settings.MEDIA_ROOT + 'avatars/'
if upload:
source = Image.open(image_path + request.user.avatar_temp)
else:
source = Image.open(image_path + request.user.avatar_original)
width, height = source.size
aspect = float(width) / float(request.POST['crop_b'])
crop_x = int(aspect * float(request.POST['crop_x']))
crop_y = int(aspect * float(request.POST['crop_y']))
crop_w = int(aspect * float(request.POST['crop_w']))
crop = source.crop((crop_x, crop_y, crop_x + crop_w, crop_y + crop_w))
if upload:
image_name, image_extension = path(request.user.avatar_temp).splitext()
else:
image_name, image_extension = path(request.user.avatar_original).splitext()
image_name = '%s_%s%s' % (request.user.pk, random_string(8), image_extension)
resizeimage(crop, settings.AVATAR_SIZES[0], image_path + image_name, info=source.info, format=source.format)
for size in settings.AVATAR_SIZES[1:]:
resizeimage(crop, size, image_path + str(size) + '_' + image_name, info=source.info, format=source.format)
request.user.delete_avatar_image()
if upload:
request.user.delete_avatar_original()
request.user.avatar_type = 'upload'
request.user.avatar_original = '%s_org_%s%s' % (request.user.pk, random_string(8), image_extension)
source.save(image_path + request.user.avatar_original)
request.user.delete_avatar_temp()
request.user.avatar_image = image_name
request.user.avatar_crop = [str(float(request.POST[x])) for x in ('crop_x', 'crop_y', 'crop_w')]
request.user.save(force_update=True)
messages.success(request, _("Your avatar has been cropped."), 'usercp_avatar')
return redirect(reverse('usercp_avatar'))
except Exception:
message = Message(_("Form contains errors."), messages.ERROR)
else:
message = Message(_("Request authorisation is invalid."), messages.ERROR)
return render_to_response('usercp/avatar_crop.html',
context_instance=RequestContext(request, {
'message': message,
'after_upload': upload,
'avatar_size': settings.AVATAR_SIZES[0],
'avatar_crop': request.user.avatar_crop if not upload else None,
'source': 'avatars/%s' % (request.user.avatar_temp if upload else request.user.avatar_original),
'tab': 'avatar'}));
示例14: settings
def settings(request, group_id=None, group_slug=None):
# Load groups and find selected group
settings_groups = SettingsGroup.objects.all().order_by('key')
if not group_id:
active_group = settings_groups[0]
group_id = active_group.pk
else:
group_id = int(group_id)
for group in settings_groups:
if group.pk == group_id:
active_group = group
break
else:
return error404(request, _('Requested settings group could not be found.'))
# Load selected group settings and turn them into form
group_settings = Setting.objects.filter(group=active_group).order_by('position')
last_fieldset = (None, [])
group_form = {'fieldsets': []}
for setting in group_settings:
# New field subgroup?
if setting.separator and last_fieldset[0] != setting.separator:
if last_fieldset[0]:
group_form['fieldsets'].append(last_fieldset)
last_fieldset = (_(setting.separator), [])
last_fieldset[1].append(setting.pk)
group_form[setting.pk] = setting.get_field()
group_form['fieldsets'].append(last_fieldset)
SettingsGroupForm = type('SettingsGroupForm', (Form,), group_form)
#Submit form
message = messages.get_message(request, 'admin_settings')
if request.method == 'POST':
form = SettingsGroupForm(request.POST, request=request)
if form.is_valid():
for setting in form.cleaned_data.keys():
misago_settings[setting] = form.cleaned_data[setting]
cache.delete('settings')
messages.success(request, _('Configuration has been changed.'), 'admin_settings')
return redirect(reverse('admin_settings', kwargs={
'group_id': active_group.pk,
'group_slug': active_group.key,
}))
else:
message = Message(form.non_field_errors()[0], messages.ERROR)
else:
form = SettingsGroupForm(request=request)
# Display settings group form
return render_to_response('settings/settings.html',
{
'message': message,
'groups': settings_groups,
'active_group': active_group,
'search_form': SearchForm(request=request),
'form': FormIterator(form),
'raw_form': form,
},
context_instance=RequestContext(request));
示例15: __call__
def __call__(self, request, target=None, slug=None):
self.request = request
# Fetch target
model = None
if target:
model = self.get_and_validate_target(target)
self.original_name = self.get_target_name(model)
if not model:
return redirect(self.get_fallback_link())
original_model = model
# Set filter
users = model.make_queryset()
total_users = users.count()
if not total_users:
messages.error(request, _('Policy "%(name)s" does not apply to any users.') % {'name': model.name}, self.admin.id)
return redirect(reverse('admin_prune_users'))
message = None
if request.method == 'POST':
deleted = 0
if request.csrf.request_secure(request):
for user in users.iterator():
if user.is_protected():
messages.info(request, _('User "%(name)s" is protected and was not deleted.') % {'name': user.username}, self.admin.id)
else:
user.delete()
deleted += 1
if deleted:
messages.success(request, ungettext(
'One user has been deleted.',
'%(deleted)d users have been deleted.',
deleted
) % {'deleted': deleted}, self.admin.id)
User.objects.resync_monitor()
else:
messages.info(request, _("No users have been deleted."), self.admin.id)
return redirect(reverse('admin_prune_users'))
else:
message = Message(_("Request authorization is invalid. Please resubmit your form."), messages.ERROR)
return render_to_response(self.get_template(),
{
'admin': self.admin,
'action': self,
'request': request,
'link': self.get_link(model),
'fallback': self.get_fallback_link(),
'messages': messages.get_messages(request, self.admin.id),
'message': message,
'tabbed': self.tabbed,
'total_users': total_users,
'target': self.get_target_name(original_model),
'target_model': original_model,
},
context_instance=RequestContext(request));