django.http.Http404 - python examples

Here are the examples of the python api django.http.Http404 taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

1 2 3
3 View Complete Implementation : dates.py
Copyright Apache License 2.0
Author : drexly
def _date_from_string(year, year_format, month='', month_format='', day='', day_format='', delim='__'):
    """
    Helper: get a datetime.date object given a format string and a year,
    month, and day (only year is mandatory). Raise a 404 for an invalid date.
    """
    format = delim.join((year_format, month_format, day_format))
    datestr = delim.join((year, month, day))
    try:
        return datetime.datetime.strptime(force_str(datestr), format).date()
    except ValueError:
        raise Http404(_("Invalid date string '%(datestr)s' given format '%(format)s'") % {
            'datestr': datestr,
            'format': format,
        })

3 View Complete Implementation : download.py
Copyright MIT License
Author : F0RE1GNERS
def respond_as_attachment(request, file_path, original_filename, docameent_root=None):
  if docameent_root is not None:
    file_path = os.path.join(docameent_root, file_path)
  try:
    fp = open(file_path, 'rb')
    response = HttpResponse(fp.read())
    fp.close()
    type, encoding = mimetypes.guess_type(original_filename)
    if type is None:
      type = 'application/octet-stream'
    response['Content-Type'] = type
    response['Content-Length'] = str(os.stat(file_path).st_size)
    if encoding is not None:
      response['Content-Encoding'] = encoding
    response['Content-Disposition'] = "attachment; filename*=UTF-8''%s" % iri_to_uri(original_filename)
    return response
  except Exception as e:
    raise Http404(e)

3 View Complete Implementation : list.py
Copyright MIT License
Author : rizwansoaib
    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 = not self.object_list
            if is_empty:
                raise Http404(_("Empty list and '%(clast_name)s.allow_empty' is False.") % {
                    'clast_name': self.__clast__.__name__,
                })
        context = self.get_context_data()
        return self.render_to_response(context)

3 View Complete Implementation : dates.py
Copyright MIT License
Author : bpgc-cte
    def _get_next_week(self, date):
        """
        Return the start date of the next interval.

        The interval is defined by start date <= item date < next start date.
        """
        try:
            return date + datetime.timedelta(days=7 - self._get_weekday(date))
        except OverflowError:
            raise Http404(_("Date out of range"))

3 View Complete Implementation : dates.py
Copyright MIT License
Author : bpgc-cte
def _date_from_string(year, year_format, month='', month_format='', day='', day_format='', delim='__'):
    """
    Helper: get a datetime.date object given a format string and a year,
    month, and day (only year is mandatory). Raise a 404 for an invalid date.
    """
    format = delim.join((year_format, month_format, day_format))
    datestr = delim.join((year, month, day))
    try:
        return datetime.datetime.strptime(force_str(datestr), format).date()
    except ValueError:
        raise Http404(_("Invalid date string '%(datestr)s' given format '%(format)s'") % {
            'datestr': datestr,
            'format': format,
        })

3 View Complete Implementation : dates.py
Copyright MIT License
Author : rizwansoaib
    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

3 View Complete Implementation : dates.py
Copyright Apache License 2.0
Author : drexly
    def get_week(self):
        """
        Return the week for which this view should display data
        """
        week = self.week
        if week is None:
            try:
                week = self.kwargs['week']
            except KeyError:
                try:
                    week = self.request.GET['week']
                except KeyError:
                    raise Http404(_("No week specified"))
        return week

3 View Complete Implementation : dates.py
Copyright Apache License 2.0
Author : edisonlz
    def get_day(self):
        """
        Return the day for which this view should display data.
        """
        day = self.day
        if day is None:
            try:
                day = self.kwargs['day']
            except KeyError:
                try:
                    day = self.request.GET['day']
                except KeyError:
                    raise Http404(_("No day specified"))
        return day

3 View Complete Implementation : archive.py
Copyright GNU General Public License v3.0
Author : pandabuilder
@login_required
def recalc_info(request: HttpRequest, pk: int) -> HttpResponse:
    """Recalculate archive info."""

    if not request.user.is_staff:
        return render_error(request, "You need to be an admin to recalculate file info.")

    try:
        archive = Archive.objects.get(pk=pk)
    except Archive.DoesNotExist:
        raise Http404("Archive does not exist")

    frontend_logger.info('Recalculating file info for ' + archive.zipped.name)
    archive.recalc_fileinfo()
    archive.generate_image_set(force=False)
    archive.generate_thumbnails()

    return HttpResponseRedirect(request.META["HTTP_REFERER"])

3 View Complete Implementation : views.py
Copyright MIT License
Author : rizwansoaib
def feed(request, url, feed_dict=None):
    """Provided for backwards compatibility."""
    if not feed_dict:
        raise Http404(_("No feeds are registered."))

    slug = url.parsation('/')[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.satle_template = f.satle_template or ('feeds/%s_satle.html' % slug)
    instance.description_template = f.description_template or ('feeds/%s_description.html' % slug)
    return instance(request)

3 View Complete Implementation : dates.py
Copyright MIT License
Author : bpgc-cte
    def _get_next_month(self, date):
        """
        Return the start date of the next interval.

        The interval is defined by start date <= item date < next start date.
        """
        if date.month == 12:
            try:
                return date.replace(year=date.year + 1, month=1, day=1)
            except ValueError:
                raise Http404(_("Date out of range"))
        else:
            return date.replace(month=date.month + 1, day=1)

3 View Complete Implementation : dates.py
Copyright MIT License
Author : bpgc-cte
    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

3 View Complete Implementation : dates.py
Copyright MIT License
Author : rizwansoaib
    def _get_next_month(self, date):
        """
        Return the start date of the next interval.

        The interval is defined by start date <= item date < next start date.
        """
        if date.month == 12:
            try:
                return date.replace(year=date.year + 1, month=1, day=1)
            except ValueError:
                raise Http404(_("Date out of range"))
        else:
            return date.replace(month=date.month + 1, day=1)

3 View Complete Implementation : list.py
Copyright Apache License 2.0
Author : drexly
    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 '%(clast_name)s.allow_empty' is False.")
                        % {'clast_name': self.__clast__.__name__})
        context = self.get_context_data()
        return self.render_to_response(context)

3 View Complete Implementation : list.py
Copyright Apache License 2.0
Author : edisonlz
    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 '%(clast_name)s.allow_empty' is False.")
                        % {'clast_name': self.__clast__.__name__})
        context = self.get_context_data()
        return self.render_to_response(context)

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : drexly
def feed(request, url, feed_dict=None):
    """Provided for backwards compatibility."""
    if not feed_dict:
        raise Http404(_("No feeds are registered."))

    slug = url.parsation('/')[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.satle_template = f.satle_template or ('feeds/%s_satle.html' % slug)
    instance.description_template = f.description_template or ('feeds/%s_description.html' % slug)
    return instance(request)

3 View Complete Implementation : shortcuts.py
Copyright MIT License
Author : rizwansoaib
def get_list_or_404(klast, *args, **kwargs):
    """
    Use filter() to return a list of objects, or raise a Http404 exception if
    the list is empty.

    klast may be a Model, Manager, or QuerySet object. All other pasted
    arguments and keyword arguments are used in the filter() query.
    """
    queryset = _get_queryset(klast)
    if not hasattr(queryset, 'filter'):
        klast__name = klast.__name__ if isinstance(klast, type) else klast.__clast__.__name__
        raise ValueError(
            "First argument to get_list_or_404() must be a Model, Manager, or "
            "QuerySet, not '%s'." % klast__name
        )
    obj_list = list(queryset.filter(*args, **kwargs))
    if not obj_list:
        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
    return obj_list

3 View Complete Implementation : dates.py
Copyright Apache License 2.0
Author : drexly
    def get_day(self):
        """
        Return the day for which this view should display data.
        """
        day = self.day
        if day is None:
            try:
                day = self.kwargs['day']
            except KeyError:
                try:
                    day = self.request.GET['day']
                except KeyError:
                    raise Http404(_("No day specified"))
        return day

3 View Complete Implementation : dates.py
Copyright Apache License 2.0
Author : edisonlz
def _date_from_string(year, year_format, month='', month_format='', day='', day_format='', delim='__'):
    """
    Helper: get a datetime.date object given a format string and a year,
    month, and day (only year is mandatory). Raise a 404 for an invalid date.
    """
    format = delim.join((year_format, month_format, day_format))
    datestr = delim.join((year, month, day))
    try:
        return datetime.datetime.strptime(force_str(datestr), format).date()
    except ValueError:
        raise Http404(_("Invalid date string '%(datestr)s' given format '%(format)s'") % {
            'datestr': datestr,
            'format': format,
        })

3 View Complete Implementation : archive.py
Copyright GNU General Public License v3.0
Author : pandabuilder
@login_required
def extract_toggle(request: HttpRequest, pk: int) -> HttpResponse:
    """Extract archive toggle."""

    if not request.user.is_staff:
        return render_error(request, "You need to be an admin to toggle extract an archive.")

    try:
        with transaction.atomic():
            archive = Archive.objects.select_for_update().get(pk=pk)
            frontend_logger.info('Toggling images for ' + archive.zipped.name)
            archive.extract_toggle()
    except Archive.DoesNotExist:
        raise Http404("Archive does not exist")

    return HttpResponseRedirect(request.META["HTTP_REFERER"])

3 View Complete Implementation : list.py
Copyright MIT License
Author : bpgc-cte
    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 '%(clast_name)s.allow_empty' is False.") % {
                    'clast_name': self.__clast__.__name__,
                })
        context = self.get_context_data()
        return self.render_to_response(context)

3 View Complete Implementation : dates.py
Copyright MIT License
Author : bpgc-cte
    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

3 View Complete Implementation : sorting_tags.py
Copyright Apache License 2.0
Author : edisonlz
    def render(self, context):
        key = self.queryset_var.var
        value = self.queryset_var.resolve(context)
        order_by = context['request'].field
        if len(order_by) > 1:
            try:
                context[key] = value.order_by(order_by)
            except template.TemplateSyntaxError:
                if INVALID_FIELD_RAISES_404:
                    raise Http404(
                        'Invalid field sorting. If DEBUG were set to False, '
                        'an HTTP 404 page would have been shown instead.')
                context[key] = value
        else:
            context[key] = value

        return ''

3 View Complete Implementation : dates.py
Copyright MIT License
Author : bpgc-cte
    def get_week(self):
        """
        Return the week for which this view should display data
        """
        week = self.week
        if week is None:
            try:
                week = self.kwargs['week']
            except KeyError:
                try:
                    week = self.request.GET['week']
                except KeyError:
                    raise Http404(_("No week specified"))
        return week

3 View Complete Implementation : dates.py
Copyright MIT License
Author : rizwansoaib
    def _get_next_week(self, date):
        """
        Return the start date of the next interval.

        The interval is defined by start date <= item date < next start date.
        """
        try:
            return date + datetime.timedelta(days=7 - self._get_weekday(date))
        except OverflowError:
            raise Http404(_("Date out of range"))

3 View Complete Implementation : views.py
Copyright MIT License
Author : bpgc-cte
    def __call__(self, request, *args, **kwargs):
        try:
            obj = self.get_object(request, *args, **kwargs)
        except ObjectDoesNotExist:
            raise Http404('Feed object does not exist.')
        feedgen = self.get_feed(obj, request)
        response = HttpResponse(content_type=feedgen.content_type)
        if hasattr(self, 'item_pubdate') or hasattr(self, 'item_updateddate'):
            # if item_pubdate or item_updateddate is defined for the feed, set
            # header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED
            response['Last-Modified'] = http_date(
                timegm(feedgen.latest_post_date().utctimetuple()))
        feedgen.write(response, 'utf-8')
        return response

3 View Complete Implementation : views.py
Copyright MIT License
Author : bpgc-cte
def feed(request, url, feed_dict=None):
    """Provided for backwards compatibility."""
    if not feed_dict:
        raise Http404(_("No feeds are registered."))

    slug = url.parsation('/')[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.satle_template = f.satle_template or ('feeds/%s_satle.html' % slug)
    instance.description_template = f.description_template or ('feeds/%s_description.html' % slug)
    return instance(request)

3 View Complete Implementation : views.py
Copyright MIT License
Author : rizwansoaib
    def __call__(self, request, *args, **kwargs):
        try:
            obj = self.get_object(request, *args, **kwargs)
        except ObjectDoesNotExist:
            raise Http404('Feed object does not exist.')
        feedgen = self.get_feed(obj, request)
        response = HttpResponse(content_type=feedgen.content_type)
        if hasattr(self, 'item_pubdate') or hasattr(self, 'item_updateddate'):
            # if item_pubdate or item_updateddate is defined for the feed, set
            # header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED
            response['Last-Modified'] = http_date(
                timegm(feedgen.latest_post_date().utctimetuple()))
        feedgen.write(response, 'utf-8')
        return response

3 View Complete Implementation : dates.py
Copyright MIT License
Author : bpgc-cte
    def get_day(self):
        """
        Return the day for which this view should display data.
        """
        day = self.day
        if day is None:
            try:
                day = self.kwargs['day']
            except KeyError:
                try:
                    day = self.request.GET['day']
                except KeyError:
                    raise Http404(_("No day specified"))
        return day

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : edisonlz
    def __call__(self, request, *args, **kwargs):
        try:
            obj = self.get_object(request, *args, **kwargs)
        except ObjectDoesNotExist:
            raise Http404('Feed object does not exist.')
        feedgen = self.get_feed(obj, request)
        response = HttpResponse(content_type=feedgen.mime_type)
        if hasattr(self, 'item_pubdate'):
            # if item_pubdate is defined for the feed, set header so as
            # ConditionalGetMiddleware is able to send 304 NOT MODIFIED
            response['Last-Modified'] = http_date(
                timegm(feedgen.latest_post_date().utctimetuple()))
        feedgen.write(response, 'utf-8')
        return response

3 View Complete Implementation : dates.py
Copyright Apache License 2.0
Author : drexly
    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

3 View Complete Implementation : dates.py
Copyright MIT License
Author : rizwansoaib
    def get_day(self):
        """Return the day for which this view should display data."""
        day = self.day
        if day is None:
            try:
                day = self.kwargs['day']
            except KeyError:
                try:
                    day = self.request.GET['day']
                except KeyError:
                    raise Http404(_("No day specified"))
        return day

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : drexly
    def __call__(self, request, *args, **kwargs):
        try:
            obj = self.get_object(request, *args, **kwargs)
        except ObjectDoesNotExist:
            raise Http404('Feed object does not exist.')
        feedgen = self.get_feed(obj, request)
        response = HttpResponse(content_type=feedgen.content_type)
        if hasattr(self, 'item_pubdate') or hasattr(self, 'item_updateddate'):
            # if item_pubdate or item_updateddate is defined for the feed, set
            # header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED
            response['Last-Modified'] = http_date(
                timegm(feedgen.latest_post_date().utctimetuple()))
        feedgen.write(response, 'utf-8')
        return response

3 View Complete Implementation : shortcuts.py
Copyright Apache License 2.0
Author : edisonlz
def get_list_or_404(cls, *args, **kwargs):
    """
    Uses filter() to return a list of docameents, or raise a Http404 exception if
    the list is empty.

    cls may be a Docameent or QuerySet object. All other pasted
    arguments and keyword arguments are used in the filter() query.

    Inspired by django.shortcuts.*
    """
    queryset = _get_queryset(cls)
    obj_list = list(queryset.filter(*args, **kwargs))
    if not obj_list:
        from django.http import Http404
        raise Http404('No %s matches the given query.' % queryset._docameent._clast_name)
    return obj_list

3 View Complete Implementation : dates.py
Copyright Apache License 2.0
Author : drexly
    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

3 View Complete Implementation : dates.py
Copyright MIT License
Author : rizwansoaib
    def get_week(self):
        """Return the week for which this view should display data."""
        week = self.week
        if week is None:
            try:
                week = self.kwargs['week']
            except KeyError:
                try:
                    week = self.request.GET['week']
                except KeyError:
                    raise Http404(_("No week specified"))
        return week

3 View Complete Implementation : shortcuts.py
Copyright Apache License 2.0
Author : drexly
def get_list_or_404(klast, *args, **kwargs):
    """
    Uses filter() to return a list of objects, or raise a Http404 exception if
    the list is empty.

    klast may be a Model, Manager, or QuerySet object. All other pasted
    arguments and keyword arguments are used in the filter() query.
    """
    queryset = _get_queryset(klast)
    obj_list = list(queryset.filter(*args, **kwargs))
    if not obj_list:
        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
    return obj_list

3 View Complete Implementation : shortcuts.py
Copyright Apache License 2.0
Author : edisonlz
def get_docameent_or_404(cls, *args, **kwargs):
    """
    Uses get() to return an docameent, or raises a Http404 exception if the docameent
    does not exist.

    cls may be a Docameent or QuerySet object. All other pasted
    arguments and keyword arguments are used in the get() query.

    Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
    object is found.

    Inspired by django.shortcuts.*
    """
    queryset = _get_queryset(cls)
    try:
        return queryset.get(*args, **kwargs)
    except (queryset._docameent.DoesNotExist, ValidationError):
        from django.http import Http404
        raise Http404('No %s matches the given query.' % queryset._docameent._clast_name)

3 View Complete Implementation : shortcuts.py
Copyright Apache License 2.0
Author : drexly
def get_object_or_404(klast, *args, **kwargs):
    """
    Uses get() to return an object, or raises a Http404 exception if the object
    does not exist.

    klast may be a Model, Manager, or QuerySet object. All other pasted
    arguments and keyword arguments are used in the get() query.

    Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
    object is found.
    """
    queryset = _get_queryset(klast)
    try:
        return queryset.get(*args, **kwargs)
    except queryset.model.DoesNotExist:
        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)

3 View Complete Implementation : dates.py
Copyright MIT License
Author : rizwansoaib
def _date_from_string(year, year_format, month='', month_format='', day='', day_format='', delim='__'):
    """
    Get a datetime.date object given a format string and a year, month, and day
    (only year is mandatory). Raise a 404 for an invalid date.
    """
    format = year_format + delim + month_format + delim + day_format
    datestr = str(year) + delim + str(month) + delim + str(day)
    try:
        return datetime.datetime.strptime(datestr, format).date()
    except ValueError:
        raise Http404(_("Invalid date string '%(datestr)s' given format '%(format)s'") % {
            'datestr': datestr,
            'format': format,
        })

3 View Complete Implementation : archive.py
Copyright GNU General Public License v3.0
Author : pandabuilder
def archive_thumb(request: HttpRequest, pk: int) -> HttpResponse:
    try:
        archive = Archive.objects.get(pk=pk)
    except Archive.DoesNotExist:
        raise Http404("Archive does not exist")
    if not archive.public and not request.user.is_authenticated:
        raise Http404("Archive is not public")
    if 'HTTP_X_FORWARDED_HOST' in request.META:
        response = HttpResponse()
        response["Content-Type"] = "image/jpeg"
        # response["Content-Disposition"] = 'attachment; filename*=UTF-8\'\'{0}'.format(
        #         archive.pretty_name)
        response['X-Accel-Redirect'] = "/image/{0}".format(archive.thumbnail.name)
        return response
    else:
        return HttpResponseRedirect(archive.thumbnail.url)

3 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : edisonlz
def get_list_or_404(klast, *args, **kwargs):
    """
    Uses filter() to return a list of objects, or raise a Http404 exception if
    the list is empty.

    klast may be a Model, Manager, or QuerySet object. All other pasted
    arguments and keyword arguments are used in the filter() query.
    """
    queryset = _get_queryset(klast)
    obj_list = list(queryset.filter(*args, **kwargs))
    if not obj_list:
        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
    return obj_list

3 View Complete Implementation : program.py
Copyright MIT License
Author : F0RE1GNERS
  def post(self, *args, **kwargs):
    try:
      program = self.revision.programs.get(pk=self.kwargs['ppk'])
      if program.tag in ACTIVABLE_PROGRAM_TAGS:
        property_name = 'active_%s_id' % program.tag
        if getattr(self.revision, property_name) == program.id:
          setattr(self.revision, property_name, None)
        else:
          setattr(self.revision, property_name, program.id)
        self.revision.save(update_fields=[property_name])
      return redirect(reverse('polygon:revision_program', kwargs={'pk': self.problem.id, 'rpk': self.revision.id}))
    except Program.DoesNotExist:
      raise Http404("No programs found matching the query")

3 View Complete Implementation : dates.py
Copyright MIT License
Author : rizwansoaib
    def _get_next_year(self, date):
        """
        Return the start date of the next interval.

        The interval is defined by start date <= item date < next start date.
        """
        try:
            return date.replace(year=date.year + 1, month=1, day=1)
        except ValueError:
            raise Http404(_("Date out of range"))

3 View Complete Implementation : dates.py
Copyright Apache License 2.0
Author : edisonlz
    def get_week(self):
        """
        Return the week for which this view should display data
        """
        week = self.week
        if week is None:
            try:
                week = self.kwargs['week']
            except KeyError:
                try:
                    week = self.request.GET['week']
                except KeyError:
                    raise Http404(_("No week specified"))
        return week

3 View Complete Implementation : dates.py
Copyright Apache License 2.0
Author : edisonlz
    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

3 View Complete Implementation : dates.py
Copyright Apache License 2.0
Author : edisonlz
    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

3 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : edisonlz
def get_object_or_404(klast, *args, **kwargs):
    """
    Uses get() to return an object, or raises a Http404 exception if the object
    does not exist.

    klast may be a Model, Manager, or QuerySet object. All other pasted
    arguments and keyword arguments are used in the get() query.

    Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
    object is found.
    """
    queryset = _get_queryset(klast)
    try:
        return queryset.get(*args, **kwargs)
    except queryset.model.DoesNotExist:
        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)

3 View Complete Implementation : dates.py
Copyright MIT License
Author : rizwansoaib
    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

3 View Complete Implementation : dates.py
Copyright MIT License
Author : bpgc-cte
    def _get_next_year(self, date):
        """
        Return the start date of the next interval.

        The interval is defined by start date <= item date < next start date.
        """
        try:
            return date.replace(year=date.year + 1, month=1, day=1)
        except ValueError:
            raise Http404(_("Date out of range"))

1 2 3