def accept_suggestion(request, unit, suggid):
try:
suggestion = unit.suggestion_set.get(id=suggid)
except ObjectDoesNotExist:
raise Http404
unit.accept_suggestion(suggestion, request.translation_project, request.user)
if "comment" in request.POST and request.POST["comment"]:
handle_suggestion_comment(request, suggestion, unit,
request.POST["comment"], "accepted")
json = {
'udbid': unit.id,
'sugid': suggid,
'user_score': request.user.public_score,
'newtargets': [target for target in unit.target.strings],
'checks': _get_critical_checks_snippet(request, unit),
}
return JsonResponse(json)
python类Http404()的实例源码
def get_object(self):
"""
Primary key lookup if pk numeric, otherwise use custom filter kwargs.
This allows us to also support build 37 lookup by chromosome, position,
reference and variant.
"""
if self.kwargs['pk'].isdigit():
return super(VariantViewSet, self).get_object()
queryset = self.filter_queryset(self.get_queryset())
filter_kwargs = self._custom_variant_filter_kwargs(self.kwargs['pk'])
if not filter_kwargs:
raise Http404('No {} matches the given query.'.format(
queryset.model._meta.object_name))
obj = get_object_or_404(queryset, **filter_kwargs)
self.check_object_permissions(self.request, obj)
return obj
def init_request(self, object_id, *args, **kwargs):
"The 'delete' admin view for this model."
self.obj = self.get_object(unquote(object_id))
if not self.has_delete_permission(self.obj):
raise PermissionDenied
if self.obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(self.opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
(self.deleted_objects, model_count, self.perms_needed, self.protected) = get_deleted_objects(
[self.obj], self.opts, self.request.user, self.admin_site, using)
def verify_step2(request, uidb64, token):
bytes_uid = urlsafe_base64_decode(uidb64)
try:
uid = int(bytes_uid)
except ValueError:
raise SuspiciousOperation('verify_step2 received invalid base64 user ID: {}'.format(
bytes_uid))
if uid != request.user.id:
raise PermissionDenied('UID mismatch - user is {}, request was for {}'.format(
request.user.id, uid))
user = get_object_or_404(models.User, pk=uid)
if not verify_token_generator.check_token(user, token):
raise Http404('token invalid')
if not user.email_verified:
user.email_verified = True
user.save()
messages.success(request, _('Your email has been verified successfully. Thanks!'))
else:
messages.info(request, _('Your email address has already been verified.'))
return redirect('index')
def convert_exception_to_response(get_response):
"""
Wrap the given get_response callable in exception-to-response conversion.
All exceptions will be converted. All known 4xx exceptions (Http404,
PermissionDenied, MultiPartParserError, SuspiciousOperation) will be
converted to the appropriate response, and all other exceptions will be
converted to 500 responses.
This decorator is automatically applied to all middleware to ensure that
no middleware leaks an exception and that the next middleware in the stack
can rely on getting a response instead of an exception.
"""
@wraps(get_response, assigned=available_attrs(get_response))
def inner(request):
try:
response = get_response(request)
except Exception as exc:
response = response_for_exception(request, exc)
return response
return inner
def get_context_data(self, **kwargs):
view = self.kwargs['view']
view_func = self._get_view_func(view)
if view_func is None:
raise Http404
title, body, metadata = utils.parse_docstring(view_func.__doc__)
if title:
title = utils.parse_rst(title, 'view', _('view:') + view)
if body:
body = utils.parse_rst(body, 'view', _('view:') + view)
for key in metadata:
metadata[key] = utils.parse_rst(metadata[key], 'model', _('view:') + view)
kwargs.update({
'name': view,
'summary': title,
'body': body,
'meta': metadata,
})
return super(ViewDetailView, self).get_context_data(**kwargs)
def flatpage(request, url):
"""
Public interface to the flat page view.
Models: `flatpages.flatpages`
Templates: Uses the template defined by the ``template_name`` field,
or :template:`flatpages/default.html` if template_name is not defined.
Context:
flatpage
`flatpages.flatpages` object
"""
if not url.startswith('/'):
url = '/' + url
site_id = get_current_site(request).id
try:
f = get_object_or_404(FlatPage, url=url, sites=site_id)
except Http404:
if not url.endswith('/') and settings.APPEND_SLASH:
url += '/'
f = get_object_or_404(FlatPage, url=url, sites=site_id)
return HttpResponsePermanentRedirect('%s/' % request.path)
else:
raise
return render_flatpage(request, f)
def serve(request, path, insecure=False, **kwargs):
"""
Serve static files below a given point in the directory structure or
from locations inferred from the staticfiles finders.
To use, put a URL pattern such as::
from django.contrib.staticfiles import views
url(r'^(?P<path>.*)$', views.serve)
in your URLconf.
It uses the django.views.static.serve() view to serve the found files.
"""
if not settings.DEBUG and not insecure:
raise Http404
normalized_path = posixpath.normpath(unquote(path)).lstrip('/')
absolute_path = finders.find(normalized_path)
if not absolute_path:
if path.endswith('/') or path == '':
raise Http404("Directory indexes are not allowed here.")
raise Http404("'%s' could not be found" % path)
document_root, path = os.path.split(absolute_path)
return static.serve(request, path, document_root=document_root, **kwargs)
def feed(request, url, feed_dict=None):
"""Provided for backwards compatibility."""
if not feed_dict:
raise Http404(_("No feeds are registered."))
slug = url.partition('/')[0]
try:
f = feed_dict[slug]
except KeyError:
raise Http404(_("Slug %r isn't registered.") % slug)
instance = f()
instance.feed_url = getattr(f, 'feed_url', None) or request.path
instance.title_template = f.title_template or ('feeds/%s_title.html' % slug)
instance.description_template = f.description_template or ('feeds/%s_description.html' % slug)
return instance(request)
def app_index(self, request, app_label, extra_context=None):
app_dict = self._build_app_dict(request, app_label)
if not app_dict:
raise Http404('The requested admin page does not exist.')
# Sort the models alphabetically within each app.
app_dict['models'].sort(key=lambda x: x['name'])
app_name = apps.get_app_config(app_label).verbose_name
context = dict(
self.each_context(request),
title=_('%(app)s administration') % {'app': app_name},
app_list=[app_dict],
app_label=app_label,
)
context.update(extra_context or {})
request.current_app = self.name
return TemplateResponse(request, self.app_index_template or [
'admin/%s/app_index.html' % app_label,
'admin/app_index.html'
], context)
# This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site.
def job_detail(request, queue_index, job_id):
queue_index = int(queue_index)
queue = get_queue_by_index(queue_index)
try:
job = Job.fetch(job_id, connection=queue.connection)
except NoSuchJobError:
raise Http404(_("Couldn't find job with this ID: %s") % job_id)
context_data = admin.site.each_context(request)
context_data.update({
'title': _("Job Detail"),
'queue_index': queue_index,
'job': job,
'queue': queue,
})
return render(request, 'django_rq/job_detail.html', context_data)
def click(request):
global clicktrack
clicktrack += 1
do_reset = (request.is_intercooler() and
request.intercooler_data.element.id == 'intro-btn2' and
request.intercooler_data.current_url.match is not None)
if do_reset:
clicktrack = 0
time = pluralize(clicktrack)
text = "<span>You clicked me {} time{}...</span>".format(clicktrack, time)
if do_reset:
text = "<span>You reset the counter!, via {}</span>".format(request.intercooler_data.trigger.id)
if not request.is_intercooler():
raise Http404("Not allowed to come here outside of an Intercooler.js request!")
resp = HttpResponse(text)
return resp
def init_request(self, object_id, *args, **kwargs):
"The 'delete' admin view for this model."
self.obj = self.get_object(unquote(object_id))
if not self.has_delete_permission(self.obj):
raise PermissionDenied
if self.obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(self.opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
(self.deleted_objects, model_count, self.perms_needed, self.protected) = get_deleted_objects(
[self.obj], self.opts, self.request.user, self.admin_site, using)
def init_request(self, object_id, *args, **kwargs):
"The 'delete' admin view for this model."
self.obj = self.get_object(unquote(object_id))
if not self.has_delete_permission(self.obj):
raise PermissionDenied
if self.obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(self.opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
(self.deleted_objects, model_count, self.perms_needed, self.protected) = get_deleted_objects(
[self.obj], self.opts, self.request.user, self.admin_site, using)
def init_request(self, object_id, *args, **kwargs):
"The 'delete' admin view for this model."
self.obj = self.get_object(unquote(object_id))
if not self.has_delete_permission(self.obj):
raise PermissionDenied
if self.obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(self.opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
(self.deleted_objects, model_count, self.perms_needed, self.protected) = get_deleted_objects(
[self.obj], self.opts, self.request.user, self.admin_site, using)
def convert_exception_to_response(get_response):
"""
Wrap the given get_response callable in exception-to-response conversion.
All exceptions will be converted. All known 4xx exceptions (Http404,
PermissionDenied, MultiPartParserError, SuspiciousOperation) will be
converted to the appropriate response, and all other exceptions will be
converted to 500 responses.
This decorator is automatically applied to all middleware to ensure that
no middleware leaks an exception and that the next middleware in the stack
can rely on getting a response instead of an exception.
"""
@wraps(get_response, assigned=available_attrs(get_response))
def inner(request):
try:
response = get_response(request)
except Exception as exc:
response = response_for_exception(request, exc)
return response
return inner
def get_context_data(self, **kwargs):
view = self.kwargs['view']
view_func = self._get_view_func(view)
if view_func is None:
raise Http404
title, body, metadata = utils.parse_docstring(view_func.__doc__)
if title:
title = utils.parse_rst(title, 'view', _('view:') + view)
if body:
body = utils.parse_rst(body, 'view', _('view:') + view)
for key in metadata:
metadata[key] = utils.parse_rst(metadata[key], 'model', _('view:') + view)
kwargs.update({
'name': view,
'summary': title,
'body': body,
'meta': metadata,
})
return super(ViewDetailView, self).get_context_data(**kwargs)
def flatpage(request, url):
"""
Public interface to the flat page view.
Models: `flatpages.flatpages`
Templates: Uses the template defined by the ``template_name`` field,
or :template:`flatpages/default.html` if template_name is not defined.
Context:
flatpage
`flatpages.flatpages` object
"""
if not url.startswith('/'):
url = '/' + url
site_id = get_current_site(request).id
try:
f = get_object_or_404(FlatPage, url=url, sites=site_id)
except Http404:
if not url.endswith('/') and settings.APPEND_SLASH:
url += '/'
f = get_object_or_404(FlatPage, url=url, sites=site_id)
return HttpResponsePermanentRedirect('%s/' % request.path)
else:
raise
return render_flatpage(request, f)
def serve(request, path, insecure=False, **kwargs):
"""
Serve static files below a given point in the directory structure or
from locations inferred from the staticfiles finders.
To use, put a URL pattern such as::
from django.contrib.staticfiles import views
url(r'^(?P<path>.*)$', views.serve)
in your URLconf.
It uses the django.views.static.serve() view to serve the found files.
"""
if not settings.DEBUG and not insecure:
raise Http404
normalized_path = posixpath.normpath(unquote(path)).lstrip('/')
absolute_path = finders.find(normalized_path)
if not absolute_path:
if path.endswith('/') or path == '':
raise Http404("Directory indexes are not allowed here.")
raise Http404("'%s' could not be found" % path)
document_root, path = os.path.split(absolute_path)
return static.serve(request, path, document_root=document_root, **kwargs)
def feed(request, url, feed_dict=None):
"""Provided for backwards compatibility."""
if not feed_dict:
raise Http404(_("No feeds are registered."))
slug = url.partition('/')[0]
try:
f = feed_dict[slug]
except KeyError:
raise Http404(_("Slug %r isn't registered.") % slug)
instance = f()
instance.feed_url = getattr(f, 'feed_url', None) or request.path
instance.title_template = f.title_template or ('feeds/%s_title.html' % slug)
instance.description_template = f.description_template or ('feeds/%s_description.html' % slug)
return instance(request)