Home > Net >  django: get HTML form value in view.py failed with empty <QueryDict: {}> and None value
django: get HTML form value in view.py failed with empty <QueryDict: {}> and None value

Time:12-29

I am new to django and follow the djangogirls tutorial. With a few modifications, I am trying to get the value from the form text field and print it in view.py and then display this value again in another "result" field in the html page.

html:

<!DOCTYPE html>
<html>
  <body>
    <form>
        <div>
            <label>num_1:</label>
            <input type = "text" name="num_1" value = "1" placeholder="Enter value">
        </div>
        <div>
           <label>num_2:</label>
            <input type = "text" name="num_2" value = "2" placeholder="Enter value">
        </div>
    </form>

        <div>
            <label>result:</label>
            {{ result }}
        </div>
    <br>
    </body>
</html>

view.py:

def post_list(request):
    # posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    num1 = request.POST.get('num_1')
    num2 = request.POST.get('num_2')
    result = int(num1) int(num2)
    print(request.POST)
    print("num1 ", num1)
    # return render(request, 'blog/post_list.html', {'posts': posts})
    return render(request, 'blog/post_list.html', {'result': result})

when I activate the local server, I got:

Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
<QueryDict: {}>
num1  None

CodePudding user response:

You need add method="post" and enter image description here

And terminal:

enter image description here

  • Related