Context Processors and Using MEDIA_URL in Templates
To use MEDIA_URL
in a template, we could pass it in through the rendering context dictionary, in our view. For example:
from django.conf import settings def my_view(request): Â Â Â Â return render(request, "template.html",\ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â {"MEDIA_URL": settings.MEDIA_URL,\ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â "username": "admin"})
This will work, but the problem is that MEDIA_URL
is a common variable that we might want to use in many places, and so we'd have to pass it through in practically every view.
Instead, we can use a context processor, which is a way of adding one or more variables automatically to the context dictionary on every render
call.
A context processor is a function that accepts...