Get values from a form

0

I'm trying to get the values out of a form that is not in the forms.py, besides this has a button to add a value, what I want is only to print the values entered on the screen, unfortunately I could not make it work.

Error message

  

local variable 'response' referenced before assignment

urls

url(r'^test', views.test),

views

def test(request):
    if request.method == "POST":
        response = ''
        for key, value in request.POST.items():
            response += '%s %s\n' % (key, value)

    return HttpResponse(response)




    return render(request, 'datos2.html')

datos2.html

<form action="/test" method="post"> {% csrf_token %}
<input type="text" name="eee">
<input type="submit">
</form>


<p>ADD VALUE</p>

<button onclick="myFunction()">ADD</button>

<script>
function myFunction() {
    var x = document.createElement("INPUT");
    x.setAttribute("type", "text");
    x.setAttribute("value", "0");
    x.setAttribute("name", "eee");
    document.body.appendChild(x);
}
</script>

At the time of executing it I get the following error

  

local variable 'response' referenced before assignment

    
asked by El arquitecto 07.10.2016 в 23:21
source

2 answers

1

Your return return HttpResponse(response) is outside the conditional, so if it does not enter the conditional variable response is never defined try this way ...

def test(request):
    if request.method == "POST":
        response = ''
        for key, value in request.POST.items():
            response += '%s %s\n' % (key, value)

        return HttpResponse(response) # nota, cuatro espacios de mas de indentación

return render(request, 'datos2.html')
    
answered by 07.10.2016 в 23:33
0

I imagine that you want to show the values that were added dynamically, but the javascript is not adding the values in the form if not in the body, which may not be sent in the request, it should be like this:

<form id="test" method="post">
    {% csrf_token %}
</form>

<p>ADD VALUE</p>

<button onclick="myFunction()">ADD</button>

<script type="text/javascript">
    function myFunction() {
        form = document.getElementById('test')
        var x = document.createElement("INPUT");
        x.setAttribute("type", "text");
        x.setAttribute("value", "0");
        x.setAttribute("name", "eee");
        form.appendChild(x)
    }
</script>

Now the logic to show the values, let's say it's fine but it's not clear, so change it a bit:

for key, value in request.POST.items():
    response = ''
    if key != 'csrfmiddlewaretoken':
         response += 'llave: %s valor:%s<br>' % (key, value)
    
answered by 09.10.2016 в 19:37