Quantcast
Viewing all articles
Browse latest Browse all 25

Django get_object_or_404 method

While we develop dynamic web applications we query data for dynamically generated pages by any unique value ( like ID,  Product Code, Slug) of that page.

In our dynamic web applications we define URLs in which we specify some parameters like ID, slug, code or anything unique to get the specified object. But if that URL cannot get any object then it will show an error which can reveal some sensitive informations of your web application.

Django get_object_or_404 method

Don’t worry. Django has some built-in functions for you to avoid these types of problem. Django get_object_or_404 method is one of those functions.

Django get_object_or_404 method will solve this problem for you. get_object_or_404 method will first call the get() method for the specific model manager, but if the object doesn’t exist then it will raise Http404.

So when you are building a web application and dynamic web pages query for any unique element but fails for any specific ID or whatever then Django get_object_or_404 method is a good choice for you.

Here is a simple example for you (assuming I have created a Django Model named Blog):

from django.shortcuts import get_object_or_404

def details_view(request):
    my_object = get_object_or_404(Blog, pk=1)

We could write the following code instead if we didn’t want to use Django get_object_or_404 method:

from django.http import Http404

def my_view(request):
    try:
        my_object = Blog.objects.get(pk=1)
    except Blog.DoesNotExist:
        raise Http404("Object does not exist.")

Using Queryset Instance

You can also pass a QuerySet instance:

my_query = Blog.objects.filter(name__startswith='A')
get_object_or_404(my_query, pk=1)

The above example is a bit contrived since it’s equivalent to doing:

get_object_or_404(Blog, name__startswith='A', pk=1)

Its a very simple function which tries to get the object based on the condition(s) you set and if it doesn’t get any object in return then it will take your user to the 404 page. That’s all you need to know about Django get_object_or_404 method.

Enjoy Django.

The post Django get_object_or_404 method appeared first on JS Tricks.


Viewing all articles
Browse latest Browse all 25

Trending Articles