Reputation: 577
I'm a beginner at django and python.
I build a model has ImageField. The attribute of ImageField is Null=True and blank=True.
In my django app code, I try to access the ImageField like this.
maker['profileImg'] = item.user.profile_pic.url
But I got an error message.
So I modify the app code like this.
try:
maker['profileImg'] = item.user.profile_pic.url
except:
maker['profileImg'] = ''
is there any other good way?
Upvotes: 0
Views: 2086
Reputation: 2320
Just use if
condition to check if there is an image or not in that particular field,
if item.user.profile_pic:
maker['profileImg'] = item.user.profile_pic.url
else:
maker['profileImg'] = ''
For one liner:
maker['profileImg'] = item.user.profile_pic.url if item.user.profile_pic else ''
Upvotes: 1
Reputation: 10256
If you want to avoid the None
value, you could use this in one-line:
profileImg = item.user.profile_pic.url or ''
EDIT
Do not store url
, store profile_pic
instead:
profileImg = item.user.profile_pic
And the when you need url:
if profileImg:
print profileImg.url # or whatever you need to di with url
Upvotes: 0