Posted: March 9th, 2010 | Author: Davo | Filed under: Django | Tags: DoesNotExist, get, ObjectDoesNotExist | No Comments »
The DoesNotExist exception is raised whenever the lookup with get() fails.
To catch this exception simply do this:
from myapp.models import User
try:
user = User.objects.get(id=666)
except User.DoesNotExist:
print 'Seems that there is not a user with id 666'
The DoesNotExist is inherited from ObjectDoesNotExist.
Knowing this we can catch an exception for multilple get() calls.
A simple example:
from django.core.exceptions import ObjectDoesNotExist
try:
user = Entry.objects.get(id=1)
blog = Blog.objects.get(id=666)
except ObjectDoesNotExist:
print "Either the User or the blog doesn't exist."
Posted: March 9th, 2010 | Author: Arif Harbott | Filed under: Django | Tags: admin, filtering, foreign key, limit_choices_to | No Comments »
A common question I get asked is how do you filter the auto generated foreign key select box in the Django. The answer is very easy you use the limit_choices_to method, which can be found on the Model Field reference page on the Django site.
Here is an example.
You want to limit the author of the news article to only show those users who are in the group admin (which is id: 1). You would use, limit_choices_to={‘groups__in’: [1]}
class News(models.Model):
headline = models.CharField(max_length=100)
author = models.ForeignKey('users.UserProfile', limit_choices_to={'groups__in': [1]})
date = models.DateTimeField()
article = models.TextField()
published = models.BooleanField()
Now when you edit a news article only the users who are in the admin group will be shown.
You can also use a Q object instead of a dictionary, which I will cover in another article.