MacPython
MacPython

Reputation: 18271

Django request.META

If I want to display more than one item of the request.META dictionary:

How can I put e.g. two in this string format:

def myurl(request):
    return HttpResponse("You are %s" % request.META['USER'], "Your IP Adress is " % request.META['REMOTE_ADDR']) 

does not work.

Also, any ideas how I can display/extract selective items of that dictionary.

If I want to run more than one via a template. How would I insert that in the html template:

e.g.

{{request.META }} . Does that works for all? How can I display them one in each line?

if I want e.g. just:

HTTP_COOKIE

QUERY_STRING

HTTP_CONNECTION

What would be the best way to display that 3 ?

Thanks!

Upvotes: 2

Views: 24972

Answers (2)

Manoj Govindan
Manoj Govindan

Reputation: 74755

Update (after reading OP's comment to this answer)

The template here is just a string with embedded format options.

1) It doesn't have to be called template

def myurl(request):
    place_holders = "You are %(user)s; your IP address is %(ipaddress)s"
    options = dict(user = request.META['USER'], ipaddress = request.META['REMOTE_ADDR'])
    return HttpResponse(place_holders % options)

2) You can do away with it altogether make it inline. This is purely a matter of coding style/preference.

def myurl(request):
    return HttpResponse("You are %s; your IP address is %s" % (request.META['USER'], request.META['REMOTE_ADDR']))

Original Answer

Quick and dirty answer to the first part of your question:

def myurl(request):
    template = "You are %(user)s; your IP address is %(ipaddress)s"
    options = dict(user = request.META['USER'], ipaddress = request.META['REMOTE_ADDR'])
    return HttpResponse(template % options)

Upvotes: 3

Nicolas Goy
Nicolas Goy

Reputation: 1430

Use RequestContext:

from django.template import RequestContext
from django.shortcuts import render_to_response


def myurl(request):
    return render_to_response('template.html', {},
                               context_instance=RequestContext(request))

You will then have access to request.META and everything it contains. You may use the debug template tag to print your context.

Upvotes: 0

Related Questions