Understand How to Use django get_object_or_404

In this tutorial, we're going to learn how to use Django get_object_or_404.

1. What is Django get_object_or_404

Get_object_or_404: is a method that returns a 404 error if the object does not exist.

2. How to Use Django get_object_or_404

Before coding example, let's first create a simple model and adding some records.

models.py:

class Comments(models.Model):
    name = models.CharField(max_length=300)
    comment = models.TextField()
    date = models.DateField(auto_now_add=False)

Adding some records:

Understand How to Use django get_object_or_404

Let's try to get a record that's not exists with the get() method and see what happens.


views.py:

def get_comment(request):

    #get comment pk = 555
    obj = Comments.objects.get(pk=555)
    return HttpResponse(obj)
    

result:

Understand How to Use django get_object_or_404

Let's do the same thing but now with the get_object_or_404 method and see the difference.


views.py

from django.shortcuts import get_object_or_404

def get_comment(request):

    #get comment idpk = 555
    obj = get_object_or_404(Comments, pk=555)
    return HttpResponse(obj)

result:

Understand How to Use django get_object_or_404

Voila!

I think you understood it!.
So if you want to get an object and you don't want to get an error when the record doesn't exist, you should use the get_object_or_404 method.

3. Customizing Django get_object_or_404 message

As you know, we can't customize the get_object_or_404 method's error, but we can do it with the Http404 exception, let's see an example.

from django.http import Http404

def get_comment(request):
    try:
        obj = Comments.objects.get(pk=555)
    except Comments.DoesNotExist:
        raise Http404("the obj does not exist.")

result:

Understand How to Use django get_object_or_404

4. How to Solve get_object_or_404 is not defined error

when you use the get_object_or_404 method without importing it, you will face this issue:

Understand How to Use django get_object_or_404

To solve this issue, you need to import the method before your view.

from django.shortcuts import get_object_or_404

# your view

English today is not an art to be mastered it's just a tool to use to get a result