Samsung Tab3
Samsung Tab3

Reputation: 1

How can i receive variables from django-template?

I want to receive variable value in my python code from django-template. I have two button Yes and No. When I click one of buttons, my python code must receive this django variables and check True or False. But I can`t find information how to take these variables. Here is my html code :

{% with word=words|random %}
<h1>{{ word }}</h1>
<h1>{{ word.word_ru }}</h1>
<form method="POST">
    {% csrf_token %}
<input type="submit" value="no" name="Answer" >
<input type="submit" value="yes" name="Answer" >
{% endwith %}

This my python-code:

def index(request):
    if request.method == "POST" and request.POST.get("Answer") == 'no':
        return render(request, "training/training.html", {})
    else:
        return render(request, "training/training.html", {})

Upvotes: 0

Views: 382

Answers (3)

Essex
Essex

Reputation: 6138

You could rewrite your code like this:

# template file

{% with word=words|random %}
<h1>{{ word }}</h1>
<h1>{{ word.word_ru }}</h1>
<form method="POST">
    {% csrf_token %}
        <input type="submit" value="no" name="answer_yes" >
        <input type="submit" value="yes" name="answer_no" >
{% endwith %}

And you views.py file:

# views file

def index(request):
    if 'answer_yes' in request.POST:
        my_answer = request.POST.get('answer_yes')
        return render(request, "training/training.html", {'Answer': my_answer})
    elif 'answer_no' in request.POST:
        my_answer = request.POST.get('answer_no')
        return render(request, "training/training.html", {'Answer': my_answer})

It should work but I didn't test it.

EDIT:

You could hide your variable like this:

<input type="hidden" value={{ word }} name="word" >

Then, get the variable value from this command:

if request.POST:
    my_answer = request.POST.get('word')

Upvotes: 1

Radek P
Radek P

Reputation: 16

Send the word variable by input type hidden or send by ajax. If I understand correctly, you want to send variable word to your view? Button value is working fine?

<form method="POST">
{% csrf_token %}
<input type="submit" value="no" name="Answer" >
<input type="submit" value="yes" name="Answer" >
<input type="hidden" value={{word}} name="word" >
</form>

Upvotes: 0

sunnky
sunnky

Reputation: 175

as follows

def test_view(request):
    answer = True if request.POST.get("Answer") == "yes" else False

Upvotes: 0

Related Questions