0

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}}

mitnosirrag
  • 163
  • 1
  • 8
  • 2
    What version of Django are you using? 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 }}`). – Mark Lavin Jun 19 '15 at 18:51
  • I had just started using 1.8 from 1.7 and didn't realize that they had made that change. That fixed my issue. Also, I didn't realize I was able to access media that way, I just switched to it and it worked perfectly, thanks for the tip. I'm having to pick up Django/Python as I go and reading the docs along the way. If you can post your comment as an answer, I will accept it. – mitnosirrag Jun 19 '15 at 19:22

1 Answers1

3

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 }}).

Mark Lavin
  • 24,664
  • 5
  • 76
  • 70