JBaba
JBaba

Reputation: 610

Get Form values in Python using Django framework

My question here is without using Model or forms.Form can we get form values on submit using Django request object.

Here is small example to explain problem.

HTML Code :

<form action="/login/" method="post">
    {% csrf_token %}
    <input type="text" id="USERNAME" class="text" value="USERNAME" >
    <input type="password" id="Password" value="Password" >
    <div class="submit">
        <input type="submit" onclick="myFunction()" value="LOGIN">
    </div>  
    <p><a href="#">Forgot Password ?</a></p>
</form>

views.py Code :

def dologin(request):
    print('i am in do login')
    print(request.method)
    print(request.POST)
    for key, value in request.POST.iteritems():
        print(key , value)

    return render(request,'webapp/login.html')

So here my key values are empty always. I have learned and capable enough to create html forms using Model and forms:Form. But to add more style changes I need to map this forms:Form object to html defined form.

Thanks in advance.

Upvotes: 0

Views: 103

Answers (3)

harmain
harmain

Reputation: 188

Please add the HTML attribute using name for every form component.

Upvotes: 0

alfredo138923
alfredo138923

Reputation: 1559

Assign a name to each input

<form action="/login/" method="post">
    {% csrf_token %}
    <input type="text" id="USERNAME" class="text" name="USERNAME" value="USERNAME" >
    <input type="password" id="Password" value="Password" name="Password" >
    <div class="submit">
        <input type="submit" onclick="myFunction()" value="LOGIN">
    </div>  
    <p><a href="#">Forgot Password ?</a></p>
</form>

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599470

HTML form elements always need a name attribute, otherwise the browser won't have any way of sending them to the backend. It's that attribute that is the key in the POST dict.

Note that any formatting you can do with HTML on its own you can also do with Django forms; you really should use them in most circumstances.

Upvotes: 0

Related Questions