Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using GET and POST variables directly within a Django template

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.

like image 910
Kelketek Avatar asked Dec 15 '12 18:12

Kelketek


2 Answers

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.

EDIT

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

like image 156
Eren T. Avatar answered Nov 01 '22 11:11

Eren T.


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}}
like image 3
suhailvs Avatar answered Nov 01 '22 12:11

suhailvs