check if internal url is reachable (200 status code)

Hi all,

I have a class based view to display some (filtered) objects. In this page I can select checkboxes to delete some records. The delete view gets the source url with parameters from the template and I use this url to redirect to the “source” page after the deletion. In the parameters of the source url there is also the number of the page:

https://mysite.test/path/?firstparameter=1&secondparameter=2&page=2

actually it’s passed without the scheme and the domain, like so:

/path/?firstparameter=1&secondparameter=2&page=2

After the deletion it can happen that the link with the page is not working (http status code 404). It is normal but how can I test in the view before the redirect if the link is working and reachable (http status code 200)?

Thanks in advance,

supermario18b

Depending upon exactly how you’ve constructed your view (function-based or class-based), you can check the URL that would be used as the “success url”.

We’d have to see the view in order to provide more specific advice.

Hi,
thank you for the answer. Here is the code that deletes the records and that has to redirect to the url to check:

class RecordDeleteView(PermissionRequiredMixin, generic.View):
    permission_required = ( "app.modify_rights", )

    def post(self, request, *args, **kwargs):
        ids_to_del = self.request.POST.getlist('id-to-del')
        current_path = self.request.POST.get('current-path')
        #current_path is something like /path/?firstparameter=1&secondparameter=2&page=2
        if ids_to_del:
            Record.objects.filter(id__in=ids_to_del).delete()
        #Here it would be perfect to check if the link is still working   
        return HttpResponseRedirect(current_path)

Using that structure (data in query variables and not in the path) as your path means that the path itself is valid - it’s the variables that need to be checked.

You would need to verify that all of firstparameter, secondparameter, and page are going to be valid at that point.

1 Like

To check if the page is valid after the deletion, I ended up subclassing “Paginator” and overriding the “validate_number” method. If the page is not found, the last page will be displayed.

class SafePaginator(Paginator):
    def validate_number(self, number):
        try:
            return super().validate_number(number)
        except EmptyPage:
            if number > 1:
                return self.num_pages
            else:
                raise

sources:
https://stackoverflow.com/questions/40835222/display-last-page-of-paginated-results-instead-of-404-using-listview/40835335
https://github.com/encode/django-vanilla-views/issues/49