Passing variable from django template to view

To add to JJK's answer, here's the detailed way to pass a variable from template to view using form.

Template :

<form action="{% url 'INI:fbpages' SocialAccount.uid %}" method="post">
..
</form>

Above, 'INI:fbpages' is the url pattern name defined in urls.py

SocialAccount.uid is the variable that you want to pass to the view.

Note that the double curly braces used in variable rendering in django templates are not used here.

View :

This variable can be directly accessed in the view as the fbuser command argument

def fbpages(request, fbuser):
..

You can only send data to Django views from the template in 4 different methods. In your case you will probably only be able to use option 1 and 4 if you don't want the information in the URL.

Since I am new to StackOverflow, I can't post more than 2 links so if you search the following post you will find more information about the advantages and disadvantages of each method.

"what is a more efficient way to pass variables from template to view in django"

1. Post

So you would submit a form with value.

    # You can retrieve your code in your views.py via
    request.POST.get('value')

2. Query Parameters

So you would pass //localhost:8000/?id=123

    # You can retrieve your code in your views.py via
    request.GET.get('id')

3. From the URL (See here for example)

So you would pass //localhost:8000/12/results/

    # urls.py
    urlpatterns = patterns(
        ...
        url(r'^(?P<question_id>\d+)/results/$', views.results, name='results'),
        ...
    )

and in your views...

    # views.py
    # To retrieve (question_id)
    def detail(request, question_id):
        ...
        return HttpResponse("blahblah")

4. Session (via cookie)

Downside of using session is you would have had to pass it to the view or set it earlier.

https://docs.djangoproject.com/en/1.7/topics/http/sessions/

    # views.py
    # Set the session variable
    request.session['uid'] = 123456

    # Retrieve the session variable
    var = request.session.get['uid']

Tags:

Django