简体   繁体   中英

MEDIA_URL in class-based view

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

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 (ie {{ model.field.url }} ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM