Django is a framework for web apps built in Python. In the following, we'll explain how to speed up image delivery in your Django app using ImageEngine.
For the purpose of this demo and practical application, we’ve created a dummy Django Web-App simulating a typical e-commerce store.
All of the code is present on Github for reference.
Preparations
At the end of the process, you'll need a delivery address. In the process of creating an engine, you'll need to provide the origin where the images are stored. If your origin doesn't exist yet, you can always set up a new engine after you've deployed your app when the images are online.
Integration
Let's have a look at what's required to integrate ImageEngine.
The urls.py file, can be left as is. No changes required:
urlpatterns = [
path('', views.store, name='store'),
path('cart', views.cart, name='cart'),
path('checkout', views.checkout, name='checkout'),
]
The view has a function for our store listing page that is self-explanatory. For adding the CDN to the template, we can add it via context from views. So we modify the views.py by adding a base context that can be extended by every view function:
BASE_CONTEXT = {
'MEDIA_CDN': settings.MEDIA_CDN,
}
def store(request):
products = Product.objects.all()
context = BASE_CONTEXT
context['products'] = products
return render(request, 'store/store.html', context)
Now we have a MEDIA_CDN URL injected into the context for the template files.
Next, we’ve template files such as store.html where we wish to display images. This can be done by prepending the media URL to the relative images. (store.html)
{%if product.image %}
<img
class="img-responsive product-image"
src="{{ MEDIA_CDN }}{{ product.image.url}}"
/>
{%else %}
<img class="thumbnail" src="{%static 'images/placeholder.png' %}" />
{% endif %}
Since MEDIA_CDN is injected into the code, we just need to make one more change i.e. add the MEDIA_CDN URL onto the Django configuration as below (settings.py):
MEDIA_CDN = env.str('MEDIA_CDN', '')
Then, in your .env file, or in Heroku in the environment variables, add your ImageEngine delivery address:
MEDIA_CDN=https://xxxxx.cdn.imgeng.in
Our Django app is now ready to be deployed.
Comments
0 comments
Please sign in to leave a comment.