Python django.http.Http404() Examples
The following are 30
code examples of django.http.Http404().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.http
, or try the search function
.
Example #1
Source File: pagination_tags.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
def render(self, context): key = self.queryset_var.var value = self.queryset_var.resolve(context) if isinstance(self.paginate_by, int): paginate_by = self.paginate_by else: paginate_by = self.paginate_by.resolve(context) paginator = Paginator(value, paginate_by, self.orphans) try: page_obj = paginator.page(context['request'].page) except InvalidPage: if INVALID_PAGE_RAISES_404: raise Http404('Invalid page requested. If DEBUG were set to ' + 'False, an HTTP 404 page would have been shown instead.') context[key] = [] context['invalid_page'] = True return '' if self.context_var is not None: context[self.context_var] = page_obj.object_list else: context[key] = page_obj.object_list context['paginator'] = paginator context['page_obj'] = page_obj return ''
Example #2
Source File: register.py From django-rest-registration with MIT License | 6 votes |
def process_verify_registration_data(input_data, serializer_context=None): if serializer_context is None: serializer_context = {} if not registration_settings.REGISTER_VERIFICATION_ENABLED: raise Http404() serializer = VerifyRegistrationSerializer( data=input_data, context=serializer_context, ) serializer.is_valid(raise_exception=True) data = serializer.validated_data signer = RegisterSigner(data) verify_signer_or_bad_request(signer) verification_flag_field = get_user_setting('VERIFICATION_FLAG_FIELD') user = get_user_by_verification_id(data['user_id'], require_verified=False) setattr(user, verification_flag_field, True) user.save() return user
Example #3
Source File: views.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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)
Example #4
Source File: views.py From django-rest-framework-docs with BSD 2-Clause "Simplified" License | 6 votes |
def get_context_data(self, **kwargs): settings = DRFSettings().settings if settings["HIDE_DOCS"]: raise Http404("Django Rest Framework Docs are hidden. Check your settings.") context = super(DRFDocsView, self).get_context_data(**kwargs) docs = ApiDocumentation(drf_router=self.drf_router) endpoints = docs.get_endpoints() query = self.request.GET.get("search", "") if query and endpoints: endpoints = [endpoint for endpoint in endpoints if query in endpoint.path] context['query'] = query context['endpoints'] = endpoints return context
Example #5
Source File: middleware.py From botbuilder-python with MIT License | 6 votes |
def process_exception(self, request, exception): if not self._settings.log_exceptions: return None if isinstance(exception, Http404): return None _, _, tb = sys.exc_info() # pylint: disable=invalid-name if tb is None or exception is None: # No actual traceback or exception info, don't bother logging. return None client = common.get_telemetry_client_with_processor( self._client.context.instrumentation_key, self._client.channel ) if hasattr(request, "appinsights"): client.context.operation.parent_id = request.appinsights.request.id client.track_exception(type(exception), exception, tb) return None
Example #6
Source File: resource.py From polls-api with MIT License | 6 votes |
def get_relations(self): paginator = self.get_paginator() try: page = paginator.page(int(self.request.GET.get('page', 1))) except EmptyPage: raise Http404() objects = page.object_list relations = { self.relation: self.get_resources(page) } relations['first'] = self.__class__() if page.has_next(): relations['next'] = self.__class__(page.next_page_number()) if page.has_previous(): relations['prev'] = self.__class__(page.previous_page_number()) if page.has_other_pages(): relations['last'] = self.__class__(paginator.num_pages) return relations
Example #7
Source File: test_hashids_field.py From django-hashid-field with MIT License | 6 votes |
def test_get_object_or_404(self): a = Artist.objects.create(name="Artist A") from django.http import Http404 # Regular lookups should succeed self.assertEqual(get_object_or_404(Artist, pk=a.id), a) self.assertEqual(get_object_or_404(Artist, pk=str(a.id)), a) # Lookups for non-existant IDs should fail with self.assertRaises(Http404): get_object_or_404(Artist, pk=-1) with self.assertRaises(Http404): get_object_or_404(Artist, pk="asdf") # int lookups should fail with self.assertRaises(Http404): self.assertEqual(get_object_or_404(Artist, pk=int(a.id)), a)
Example #8
Source File: reset_password.py From django-rest-registration with MIT License | 6 votes |
def process_reset_password_data(input_data, serializer_context=None): if serializer_context is None: serializer_context = {} if not registration_settings.RESET_PASSWORD_VERIFICATION_ENABLED: raise Http404() serializer = ResetPasswordSerializer( data=input_data, context=serializer_context, ) serializer.is_valid(raise_exception=True) data = serializer.validated_data.copy() password = data.pop('password') data.pop('password_confirm', None) signer = ResetPasswordSigner(data) verify_signer_or_bad_request(signer) user = get_user_by_verification_id(data['user_id'], require_verified=False) user.set_password(password) user.save()
Example #9
Source File: users.py From django-rest-registration with MIT License | 6 votes |
def get_user_by_lookup_dict( lookup_dict, default=_RAISE_EXCEPTION, require_verified=True): verification_enabled = registration_settings.REGISTER_VERIFICATION_ENABLED verification_flag_field = get_user_setting('VERIFICATION_FLAG_FIELD') user_class = get_user_model() kwargs = {} kwargs.update(lookup_dict) if require_verified and verification_enabled and verification_flag_field: kwargs[verification_flag_field] = True try: user = get_object_or_404(user_class.objects.all(), **kwargs) except Http404: if default is _RAISE_EXCEPTION: raise UserNotFound() return default else: return user
Example #10
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def index(request: HttpRequest, course_slug: str, activity_slug: str) -> HttpResponse: role = request.member.role offering = get_object_or_404(CourseOffering, slug=course_slug) activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False) if role in ['INST', 'TA']: quiz = Quiz.objects.filter(activity=activity).first() # will be None if no quiz created for this activity if not quiz: # no quiz created? Only option is to create. return redirect('offering:quiz:edit', course_slug=course_slug, activity_slug=activity_slug) return _index_instructor(request, offering, activity, quiz) elif role == 'STUD': quiz = get_object_or_404(Quiz, activity=activity) # will 404 if no quiz created for this activity return _index_student(request, offering, activity, quiz) else: raise Http404()
Example #11
Source File: views.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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)
Example #12
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def submitted_file(request: HttpRequest, course_slug: str, activity_slug: str, userid: str, answer_id: str, secret: str) -> StreamingHttpResponse: offering = get_object_or_404(CourseOffering, slug=course_slug) activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False) member = get_object_or_404(Member, ~Q(role='DROP'), find_member(userid), offering__slug=course_slug) answer = get_object_or_404(QuestionAnswer, question__quiz__activity=activity, student=member, id=answer_id) real_secret = answer.answer['data'].get('secret', '?') if real_secret != '?' and secret == real_secret: return _return_submitted_file(answer.answer['data'], answer.file.open('rb')) else: # It's not the current submission, but an instructor looking at history might be trying to find an old one... submissions = QuizSubmission.objects.filter(quiz__activity=activity, student=member) for qs in submissions: for answer_config in qs.config['answers']: version_id, answer_id, a = answer_config if not isinstance(a['data'], dict): continue real_secret = a['data'].get('secret', '?') if answer.question_version_id == version_id and answer.id == answer_id and real_secret != '?' and secret == real_secret: # aha! Temporarily replace answer.file with the old version (without saving) so we can return it answer.file = a['filepath'] return _return_submitted_file(a['data'], answer.file.open('rb')) raise Http404()
Example #13
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def file_field_download_unauth(request, form_slug, formsubmit_slug, file_id, action, secret): """ Version of file_field_download that doesn't require authentication, but does require knowing the "secret" URL component. Used to provide URLs in the CSV export. """ file_sub = get_object_or_404(FieldSubmissionFile, field_submission__sheet_submission__form_submission__slug=formsubmit_slug, field_submission__sheet_submission__form_submission__form__slug=form_slug, id=file_id) form_submission = file_sub.field_submission.sheet_submission.form_submission field_sub = file_sub.field_submission if ('secret' not in field_sub.data) \ or (not field_sub.data['secret']) \ or (len(field_sub.data['secret']) != FILE_SECRET_LENGTH) \ or (field_sub.data['secret'] != secret): raise Http404 return _file_field_download(form_submission, file_sub, action)
Example #14
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def change_grade_status(request, course_slug, activity_slug, userid): """ Grade status form. Calls numeric/letter view as appropriate. """ course = get_object_or_404(CourseOffering, slug=course_slug) acts = all_activities_filter(course, slug=activity_slug) if len(acts) != 1: raise Http404('No such Activity.') activity = acts[0] if isinstance(activity, NumericActivity): return _change_grade_status_numeric(request, course, activity, userid) elif isinstance(activity, LetterActivity): return _change_grade_status_letter(request, course, activity, userid) else: raise Http404('Unknown activity type.')
Example #15
Source File: exceptions.py From controller with MIT License | 6 votes |
def custom_exception_handler(exc, context): # give more context on the error since DRF masks it as Not Found if isinstance(exc, Http404): set_rollback() return Response(str(exc), status=status.HTTP_404_NOT_FOUND) # Call REST framework's default exception handler after specific 404 handling, # to get the standard error response. response = exception_handler(exc, context) # No response means DRF couldn't handle it # Output a generic 500 in a JSON format if response is None: logging.exception('Uncaught Exception', exc_info=exc) set_rollback() return Response({'detail': 'Server Error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) # log a few different types of exception instead of using APIException if isinstance(exc, (DeisException, ServiceUnavailable, HealthcheckException)): logging.exception(exc.__cause__, exc_info=exc) return response
Example #16
Source File: pagination_tags.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
def render(self, context): key = self.queryset_var.var value = self.queryset_var.resolve(context) if isinstance(self.paginate_by, int): paginate_by = self.paginate_by else: paginate_by = self.paginate_by.resolve(context) paginator = Paginator(value, paginate_by, self.orphans) try: page_obj = paginator.page(context['request'].page) except InvalidPage: if INVALID_PAGE_RAISES_404: raise Http404('Invalid page requested. If DEBUG were set to ' + 'False, an HTTP 404 page would have been shown instead.') context[key] = [] context['invalid_page'] = True return '' if self.context_var is not None: context[self.context_var] = page_obj.object_list else: context[key] = page_obj.object_list context['paginator'] = paginator context['page_obj'] = page_obj return ''
Example #17
Source File: list.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def paginate_queryset(self, queryset, page_size): """ Paginate the queryset, if needed. """ paginator = self.get_paginator( queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty()) page_kwarg = self.page_kwarg page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 try: page_number = int(page) except ValueError: if page == 'last': page_number = paginator.num_pages else: raise Http404(_("Page is not 'last', nor can it be converted to an int.")) try: page = paginator.page(page_number) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage as e: raise Http404(_('Invalid page (%(page_number)s): %(message)s') % { 'page_number': page_number, 'message': str(e) })
Example #18
Source File: pagination_tags.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
def render(self, context): key = self.queryset_var.var value = self.queryset_var.resolve(context) if isinstance(self.paginate_by, int): paginate_by = self.paginate_by else: paginate_by = self.paginate_by.resolve(context) paginator = Paginator(value, paginate_by, self.orphans) try: page_obj = paginator.page(context['request'].page) except InvalidPage: if INVALID_PAGE_RAISES_404: raise Http404('Invalid page requested. If DEBUG were set to ' + 'False, an HTTP 404 page would have been shown instead.') context[key] = [] context['invalid_page'] = True return '' if self.context_var is not None: context[self.context_var] = page_obj.object_list else: context[key] = page_obj.object_list context['paginator'] = paginator context['page_obj'] = page_obj return ''
Example #19
Source File: list.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() allow_empty = self.get_allow_empty() if not allow_empty: # When pagination is enabled and object_list is a queryset, # it's better to do a cheap query than to load the unpaginated # queryset in memory. if (self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists')): is_empty = not self.object_list.exists() else: is_empty = len(self.object_list) == 0 if is_empty: raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.") % {'class_name': self.__class__.__name__}) context = self.get_context_data() return self.render_to_response(context)
Example #20
Source File: delete.py From StormOnline with Apache License 2.0 | 6 votes |
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)
Example #21
Source File: dates.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def get_dated_queryset(self, **lookup): """ Get a queryset properly filtered according to `allow_future` and any extra lookup kwargs. """ qs = self.get_queryset().filter(**lookup) date_field = self.get_date_field() allow_future = self.get_allow_future() allow_empty = self.get_allow_empty() paginate_by = self.get_paginate_by(qs) if not allow_future: now = timezone.now() if self.uses_datetime_field else timezone_today() qs = qs.filter(**{'%s__lte' % date_field: now}) if not allow_empty: # When pagination is enabled, it's better to do a cheap query # than to load the unpaginated queryset in memory. is_empty = len(qs) == 0 if paginate_by is None else not qs.exists() if is_empty: raise Http404(_("No %(verbose_name_plural)s available") % { 'verbose_name_plural': force_text(qs.model._meta.verbose_name_plural) }) return qs
Example #22
Source File: dates.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def get_date_list(self, queryset, date_type=None, ordering='ASC'): """ Get a date list by calling `queryset.dates/datetimes()`, checking along the way for empty lists that aren't allowed. """ date_field = self.get_date_field() allow_empty = self.get_allow_empty() if date_type is None: date_type = self.get_date_list_period() if self.uses_datetime_field: date_list = queryset.datetimes(date_field, date_type, ordering) else: date_list = queryset.dates(date_field, date_type, ordering) if date_list is not None and not date_list and not allow_empty: name = force_text(queryset.model._meta.verbose_name_plural) raise Http404(_("No %(verbose_name_plural)s available") % {'verbose_name_plural': name}) return date_list
Example #23
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def export_marks(request, course_slug, activity_slug): """ Export JSON marking data """ course = get_object_or_404(CourseOffering, slug=course_slug) acts = all_activities_filter(course, slug=activity_slug) if len(acts) != 1: raise Http404('No such Activity.') activity = acts[0] data = _mark_export_data(activity) response = HttpResponse(content_type='application/json') response['Content-Disposition'] = 'inline; filename="%s-%s.json"' % (course.slug, activity.slug) json.dump({'marks': data}, response, cls=_DecimalEncoder, indent=1) return response
Example #24
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def mark_all_students(request, course_slug, activity_slug): """ Mark the whole class (by student). Calls numeric/letter view as appropriate. """ course = get_object_or_404(CourseOffering, slug = course_slug) acts = all_activities_filter(course, slug=activity_slug) if len(acts) != 1: raise Http404('No such Activity.') activity = acts[0] if isinstance(activity, NumericActivity): return _mark_all_students_numeric(request, course, activity) elif isinstance(activity, LetterActivity): return _mark_all_students_letter(request, course, activity) else: raise Http404('Unknown activity type.')
Example #25
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def mark_all_groups(request, course_slug, activity_slug): """ Mark the whole class (by group). Calls numeric/letter view as appropriate. """ course = get_object_or_404(CourseOffering, slug = course_slug) acts = all_activities_filter(course, slug=activity_slug) if len(acts) != 1: raise Http404('No such Activity.') activity = acts[0] if isinstance(activity, NumericActivity): return _mark_all_groups_numeric(request, course, activity) elif isinstance(activity, LetterActivity): return _mark_all_groups_letter(request, course, activity) else: raise Http404('Unknown activity type.')
Example #26
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def reopen_submission(request, form_slug, formsubmit_slug): # The wording here is tricky. The _formsubmission_find_and_authz method only returns "is_advisor" if you are # *only* an advisor, but not in the form group that owns the form. If you are in the form group, is_advisor is # false, and form_submission will be the instance we want to work on. form_submission, is_advisor = _formsubmission_find_and_authz(request, form_slug, formsubmit_slug) if not form_submission: raise Http404 # Therefore, if you're not a supervisor and you had a form_submission returned, you're in the form group and # can re-open it. can_reopen = not is_advisor and form_submission.status == 'DONE' if can_reopen and request.method == 'POST': form_submission.reopen(requester=request.user.username) messages.success(request, "Form re-opened") l = LogEntry(userid=request.user.username, description=("Re-opened Form Submission %s") % form_submission, related_object=form_submission) l.save() else: messages.error(request, "The form could no be re-opened. Perhaps it was already re-opened, or you do not " "have permission to perform this action.") return HttpResponseRedirect(reverse('onlineforms:view_submission', kwargs={'form_slug': form_slug, 'formsubmit_slug': formsubmit_slug}))
Example #27
Source File: InstanceHistoryViewSet.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def filter_queryset(self, queryset): try: fsform = FieldSightXF.objects.get(pk=self.kwargs.get('form_pk')) except FieldSightXF.DoesNotExist: raise Http404("No Responces matches the given query.") if fsform.site is None: return queryset.filter(site_id=self.kwargs.get('site_pk'), project_fxf_id=self.kwargs.get('form_pk')).order_by('-date') return queryset.filter(site_id=self.kwargs.get('site_pk'), site_fxf_id=self.kwargs.get('form_pk')).order_by('-date')
Example #28
Source File: dates.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def get_year(self): """ Return the year for which this view should display data. """ year = self.year if year is None: try: year = self.kwargs['year'] except KeyError: try: year = self.request.GET['year'] except KeyError: raise Http404(_("No year specified")) return year
Example #29
Source File: detail.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def get_object(self, queryset=None): """ Returns the object the view is displaying. By default this requires `self.queryset` and a `pk` or `slug` argument in the URLconf, but subclasses can override this to return any object. """ # Use a custom queryset if provided; this is required for subclasses # like DateDetailView if queryset is None: queryset = self.get_queryset() # Next, try looking up by primary key. pk = self.kwargs.get(self.pk_url_kwarg, None) slug = self.kwargs.get(self.slug_url_kwarg, None) if pk is not None: queryset = queryset.filter(pk=pk) # Next, try looking up by slug. if slug is not None and (pk is None or self.query_pk_and_slug): slug_field = self.get_slug_field() queryset = queryset.filter(**{slug_field: slug}) # If none of those are defined, it's an error. if pk is None and slug is None: raise AttributeError("Generic detail view %s must be called with " "either an object pk or a slug." % self.__class__.__name__) try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: raise Http404(_("No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name}) return obj
Example #30
Source File: dates.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def get_month(self): """ Return the month for which this view should display data. """ month = self.month if month is None: try: month = self.kwargs['month'] except KeyError: try: month = self.request.GET['month'] except KeyError: raise Http404(_("No month specified")) return month