Django-imagekit - best way to show default image?

I am using django-imagekit to resize my user avatars and right now to display the default avatar (if the user has not uploaded his / her avatar) I do this:

views.py

try: usr_avatar = UsrAvatar.objects.get(user=request.user.id) except UsrAvatar.DoesNotExist: usr_avatar = UsrAvatar.objects.get(id='0') 

template.html

 <img src="{{ usr_avatar.avatar_image.url }}" > 

This works fine, but every time the user didn’t upload their avatar, I ended up in the database for the default avatar image.

Is there a way to eliminate getting into the database when the user does not have an avatar image uploaded in some way, attributing a default image link to usr_avatar or just doing something in template.html? Thanks!

+4
source share
1 answer

Apt username asked your question!

You can create a context processor that provides a default avatar for each template and just make sure the context handler caches the image

settings.py

 TEMPLATE_CONTEXT_PROCESSORS = ( ... 'myapp.context_processors.default_avatar', ... ) 

Myapp / context_processors.py

 from django.core.cache import cache def default_avatar(request): default_avatar = cache.get('default_avatar', False) if not default_avatar: default_avatar = UsrAvatar.object.get(id='0') return { 'default_avatar' : default_avatar } 

Now the template variable 'default_avatar' is available in each template:

 {% if usr_avatar %} {{ usr_avatar }} {% else %} {{ default_avatar }} {% endif %} 

Or just use the cache in the original request:

 try: usr_avatar = UsrAvatar.objects.get(user=request.user.id) except UsrAvatar.DoesNotExist: usr_avatar = cache.get('default_avatar', False) if not usr_avatar: usr_avatar = UsrAvatar.objects.get(id='0') 

But finally, it would be even better not to leave the default avatar in the database at all, but instead just write a context processor, as described above, but instead of getting the default avatar from the database, just have a static image URL

 from django.conf import settings def default_avatar(request): return { 'default_avatar' : '%simages/default_avatar.jpg' % settings.STATIC_URL } 
+6
source

Source: https://habr.com/ru/post/1379780/


All Articles