开发者

redirect to another page instead of recieving Django standarf 404 error

开发者 https://www.devze.com 2023-01-06 10:26 出处:网络
i have somethinglike this in my views.py instance = get_object_or_404(register,pk=request.user.id) Now if there is 开发者_运维百科no related object against this user i receive i standard django 40

i have something like this in my views.py

    instance = get_object_or_404(register,pk=request.user.id)

Now if there is 开发者_运维百科no related object against this user i receive i standard django 404 eror saying no matches found. what i want here is instead of receiving this 404 error redirect it to another page say "something.html". but i dont know how. i am using method = "POST" is there any way to redirect it to other page instead of receiving a 404 error


using a try/except block you can redirect if the object is not found

try:
    instance = register.get(pk=request.user.id)
except register.DoesNotExist:
    return HttpResponseRedirect('url that renders something.html')   

FYI, definition of django get_object_or_404 function looks like this

def get_object_or_404(klass, *args, **kwargs):
    """ 
    Uses get() to return an object, or raises a Http404 exception if the object
    does not exist.

    klass may be a Model, Manager, or QuerySet object. All other passed
    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(klass)
    try:
        return queryset.get(*args, **kwargs)
    except queryset.model.DoesNotExist:
        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)

from the docs, If you raise Http404 at any point in a view function, Django will catch it and return the standard error page for your application, along with an HTTP error code 404.

look at customizing error views if you want to render a custom 404.html based on the context variables


Depending on what the Big Picture is, you might want to look at django.contrib.flatpages and see what they are doing. Basically they are dealing with the 404 in middleware and then looking at the path to decided if there is something they can return. I have used variations on this on a couple of sites.

0

精彩评论

暂无评论...
验证码 换一张
取 消