120๐
try:
thepost = Content.objects.get(name="test")
except Content.DoesNotExist:
thepost = None
Use the model DoesNotExist exception
37๐
Often, it is more useful to use the Django shortcut function get_object_or_404
instead of the API directly:
from django.shortcuts import get_object_or_404
thepost = get_object_or_404(Content, name='test')
Fairly obviously, this will throw a 404 error if the object cannot be found, and your code will continue if it is successful.
- [Django]-Readonly models in Django admin interface?
- [Django]-Django File upload size limit
- [Django]-Check permission inside a template in Django
18๐
You can also catch a generic DoesNotExist. As per the docs at http://docs.djangoproject.com/en/dev/ref/models/querysets/
from django.core.exceptions import ObjectDoesNotExist
try:
e = Entry.objects.get(id=3)
b = Blog.objects.get(id=1)
except ObjectDoesNotExist:
print "Either the entry or blog doesn't exist."
- [Django]-When to use get, get_queryset, get_context_data in Django?
- [Django]-How can I unit test django messages?
- [Django]-How to set up a PostgreSQL database in Django
12๐
Another way of writing:
try:
thepost = Content.objects.get(name="test")
except Content.DoesNotExist:
thepost = None
is simply:
thepost = Content.objects.filter(name="test").first()
Note that the two are not strictly the same. Manager method get
will raise not only an exception in the case thereโs no record youโre querying for but also when multiple records are found. Using first
when there are more than one record might fail your business logic silently by returning the first record.
- [Django]-Images from ImageField in Django don't load in template
- [Django]-Django: Multiple forms possible when using FormView?
- [Django]-How to disable Django's CSRF validation?
8๐
Catch the exception
try:
thepost = Content.objects.get(name="test")
except Content.DoesNotExist:
thepost = None
alternatively you can filter, which will return a empty list if nothing matches
posts = Content.objects.filter(name="test")
if posts:
# do something with posts[0] and see if you want to raise error if post > 1
- [Django]-Django model "doesn't declare an explicit app_label"
- [Django]-HTML โ How to do a Confirmation popup to a Submit button and then send the request?
- [Django]-Django: Set foreign key using integer?
4๐
Handling exceptions at different points in your views could really be cumbersome..What about defining a custom Model Manager, in the models.py file, like
class ContentManager(model.Manager):
def get_nicely(self, **kwargs):
try:
return self.get(kwargs)
except(KeyError, Content.DoesNotExist):
return None
and then including it in the content Model class
class Content(model.Model):
...
objects = ContentManager()
In this way it can be easily dealt in the views i.e.
post = Content.objects.get_nicely(pk = 1)
if post != None:
# Do something
else:
# This post doesn't exist
- [Django]-Bypass confirmation prompt for pip uninstall
- [Django]-How to create a fixture file
- [Django]-Should I be adding the Django migration files in the .gitignore file?
4๐
There are essentially two ways you can do this. The first approach is more verbose as it doesnโt use any shortcuts
:
from django.http import Http404
from .models import Content
try:
thepost = Content.objects.get(name="test")
except Content.DoesNotExist:
raise Http404("Content does not exist")
Now since this sort of operation (i.e. get an object or raise 404 if it does not exist) is quite common in Web Development, Django offers a shortcut called get_object_or_404
that will get()
the requested object or raise Http404
in case it is not found:
from django.shortcuts import get_object_or_404
from .models import Content
thepost = get_object_or_404(Content, name="test")
Likewise for lists of objects, you can use get_list_or_404()
function that makes use of filter()
instead of get()
and in case the returned list is empty, Http404
will be raised.
- [Django]-Get count of related model efficiently in Django
- [Django]-How to use if/else condition on Django Templates?
- [Django]-How do you configure Django to send mail through Postfix?
3๐
Raising a Http404 exception works great:
from django.http import Http404
def detail(request, poll_id):
try:
p = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise Http404
return render_to_response('polls/detail.html', {'poll': p})
- [Django]-Django โ How to rename a model field using South?
- [Django]-Write only, read only fields in django rest framework
- [Django]-Django โ accessing the RequestContext from within a custom filter