The DoesNotExist exception is raised when an object is not found for the given parameters of a query. Django provides a DoesNotExist exception as an attribute of each model class to identify the class of object that could not be found and to allow you to catch a particular model class with try/except.
Retrieving Single Objects from QuerySets We can do this using the get() method. The get() returns the single object directly. Let's see the following example. As we can see in both examples, we get the single object not a queryset of a single object.
Maybe you have no Comments record with such primary key, then you should use this code:
try:
comment = Comment.objects.get(pk=comment_id)
except Comment.DoesNotExist:
comment = None
your line raising the error is here:
comment = Comment.objects.get(pk=comment_id)
you try to access a non-existing comment.
from django.shortcuts import get_object_or_404
comment = get_object_or_404(Comment, pk=comment_id)
Instead of having an error on your server, your user will get a 404 meaning that he tries to access a non existing resource.
Ok up to here I suppose you are aware of this.
Some users (and I'm part of them) let tabs running for long time, if users are authorized to delete data, it may happens. A 404 error may be a better error to handle a deleted resource error than sending an email to the admin.
Other users go to addresses from their history, (same if data have been deleted since it may happens).
You can use this:
comment = Comment.objects.filter(pk=comment_id)
You may try this way. just use a function to get your object
def get_object(self, id):
try:
return Comment.objects.get(pk=id)
except Comment.DoesNotExist:
return False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With