MEDIA_URL in class-based view

119 views Asked by At

I'm not able to access MEDIA_URL in my class-based view.

My understanding has been that I would create my view, and my context processor would provide it into my function-based view. Now I'm trying to switch to class-based, and I no longer have access to MEDIA_URL.

Do context processors not work with class-based views? Do I have to add it to my context manually now?

Here are my processors:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.request',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.request',
)

My previous views looked something like:

def my_view(request):
    context = {
        "foo": "bar"
    }
    return render(request, 'index.html', context)

And I would be able to use {{MEDIA_URL}}.

My class-based view looks like:

class MyView(View):
    def get(self, request):
        context = {
            "foo": "bar"
        }
        return render(request, 'index.html', context)

And I cannot access {{MEDIA_URL}}

1

There are 1 answers

0
Mark Lavin On BEST ANSWER

Django 1.8 moved the configuration of TEMPLATE_CONTEXT_PROCESSORS to the TEMPLATES setting. Beyond that I don't think you shouldn't need to access MEDIA_URL in the template. It's a bad code smell to me. You should be using the url generated from the file storage api (i.e. {{ model.field.url }}).