Issue
I have a News model, where each instance has a unique date. Which means that every day has exactly one News-instance related to it. I am redirecting to the detail-view of the News-instance from the navbar.
To achieve this am I using a context_processor. The context_processor.py file looks like this:
from news.models import TodayNews
import datetime
def todays_news(request):
todays_news = TodayNews.objects.get(date=datetime.date.today())
return {'news': todays_news}
This works completely fine as long as the News model has an instance on that particular date. Otherwise it returns the following error (which is very logical):
TodayNews matching query does not exist.
My question is, how can I do something different if the query is empty, for example if one particular date does not have a news-instance? What should I return instead of 'news': todays_news
?
Solution
You can work with a try
-except
to return None
in case the TodayNews
object is not found:
from news.models import TodayNews
import datetime
def todays_news(request):
try:
todays_news = TodayNews.objects.get(date=datetime.date.today())
except TodayNews.DoesNotExist:
todays_news = None
return {'news': todays_news}
You can also use .first()
[Django-doc] to return the first item, this will return None
if no item can be found:
from news.models import TodayNews
import datetime
def todays_news(request):
todays_news = TodayNews.objects.filter(date=datetime.date.today()).first()
return {'news': todays_news}
Answered By - Willem Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.