0

I have the following code in one of my templates.

<html>
<body>
    <script>
        var val1 = 10;
        var val2 = 20;
    </script>
    <a href="/generate/">Generate</a>
</body>
</html>

I wish to use the values val1 and val2 in the generate function in the views.py file. It would be something like this.

def generate(request):
    # do something with val1 and val2

I am lost as to how I can pass these values to the function. What is the best practice for this, should I try to retrieve the information through URL parameters? Or perhaps I should just remove the Javascript and do everything in Python directly in the generate() function?

Thank you for your help!

2 Answers 2

3

You need to apply HTTP methods such as GET or POST.

use this code in view template (example - index.html):

<html>
<body>
    <form method="post" action="/generate">
        {% csrf_token %}
        <input type="number" name="val1" value="10">
        <input type="number" name="val2" value="20">
        <input type="submit" value="generate">
    </form>
</body>
</html>

and use this code in views.py:

def index(request):
    return render_to_response('index.html', RequestContext(request))

def generate(request):
    val1 = request.POST.get('val1', 0)
    val2 = request.POST.get('val2', 0)
    sum = val1 + val2

    return HttpResponse(str(sum))

This link is helpful for you: https://docs.djangoproject.com/en/dev/topics/forms/

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

Comments

2

Pass the parameters using GET:

<html>
    <body>
        <a href="/generate/?val1=10&val2=20">Generate</a>
    </body>
</html>

Now you can access them in view using request attribute:

def generate(request):
    if request.method == 'GET':
        val1 = request.GET.get('val1')
        val2 = request.GET.get('val2')
        #futher code

https://docs.djangoproject.com/en/dev/ref/request-response/#

1 Comment

I used this as it seems simpler and cleaner than using a form. Thank you!

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.