I want to be able to access a bit of information that someone places in a GET variable right in the template of a page (HTML escaped, of course.) How would I go about doing this? I know you can grab this information with views, but in this case, I'd rather handle it HTML side.
You can pass that information from view to the template just as passing another variable. When you are rendering your template, just add a variable and pass request.GET
QueryDict. You will be able to access all of the GET parameters within your template.
direct_to_template
automatically includes RequestContext(request)
so you will be able to use all of your context instances in your settings. Please add 'django.core.context_processors.request'
in your TEMPLATE_CONTEXT_PROCESSORS
in settings.py. Afterwards, you will be able to use access Django's HttpRequest by {{ request }}
in your template. Example settings, urls, and template are below:
settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
# these are the default values from django. I am not sure whether they
# are overritten when setting this variable, so I am including them "django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages"
)
urls.py
urlpatterns = patterns('django.views.generic.simple',
url(r'^about/$', 'direct_to_template', {'template':
'about.html'}),
)
about.html
Your request is: <br /><br />
{{ request.GET }}
Please also see the documentation about the topic:
https://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext
https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATE_CONTEXT_PROCESSORS
In new Django you can use directly in template like:
if post request with request.POST['name'] in view.py, in template you can use:
{{request.POST.name}}
if get request in template you can use:
{{request.GET.name}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With