14

In Django I want to add a variable to the request. i.e,

def update_name(request):
    names = Employee.objects.filter()
    if names.count() > 0:
        request.update({"names": name })
    return render_to_response('chatlist/newchat.html',
        context_instance=RequestContext(request, {'form': form,'msg': msg}))

Is this the right way to add a variable to the request? If not, how should I do it?

Also, how can I retrieve the same value in the templates page? i.e,

alert ("{{request.names['somename']}}");

2 Answers 2

17

The example you have given is wrong because

  1. there is no request.update function
  2. You are using name variable which you haven't assigned anywhere?

Anyway, in python you can simply assign attributes, e.g.

 def update_name(request):
     names = Employee.objects.filter()
     if(names.count() > 0): 
         request.names = names
 return render_to_response('chatlist/newchat.html', context_instance=RequestContext(request,{'form': form,'msg' : msg}))

Also you don't even need to assign to request, why can't you just pass it to template e.g.

def update_name(request):
    names = Employee.objects.filter()
     return render_to_response('chatlist/newchat.html', context_instance=RequestContext(request,{'form': form,'msg' : msg, 'names': names}))

And in the template page you can access request.name, though if you are doing this just to have a variable available in template page, it is not the best way, you can pass context dict to a template page.

Edit: Also note that before using request in template you need to pass it somehow, it is not available by default see http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext

Sign up to request clarification or add additional context in comments.

Comments

2

Working Code !!

Assume a variable named my_name. I will add this to get and post requests.

my_name = "Nidhi"

To add variable in Get request

_mutable = request.GET._mutable
request.GET._mutable = True
request.GET['my_name'] = my_name

To add variable in POST request

_mutable = request.POST._mutable
request.POST._mutable = True
request.POST['my_name'] = my_name

Now here in request there is a variable added name my_name. To get its value use below code -

request.GET.get("my_name")    # get request variable value in GET request
request.GET.get("my_name")    # get request variable value in POST request

Output : Nidhi

1 Comment

Not a Django expert by far but whenever I see access of "private" (_) members in Python in general I am wondering whether that's the way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.