Accessing request.META.SERVER_NAME in template

2019-08-09 10:23发布

问题:

I call a template like this from my view:

return render_to_response('mytemplate.html', context_instance=RequestContext(request))

I'm trying to access the hostname of my current server (in this case, localhost), but it just prints blank when I place {{request.META.SERVER_NAME}} in the template.

In my settings.py file, I don't have any TEMPLATE_CONTEXT_PROCESSORS defined. I'm not sure if I need to specify anything there, or if that could solve the problem.

回答1:

You have to add the request context processor to have it added to the template context automatically. Or you could explicitly add the request to the context dictionary render_to_response('foo', {'request': request})

https://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-request

Note that if you add the request context processor, you should remember to add the defaults as well.