Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access form data of post method in Django

Tags:

python

django

I want to access post method data in views.py. I am following procedure of using pure html for form not Django form class. I tried the solution MultiValueDictKeyError in Django but still it is not working. Help me out

index.html

<form action="{% url "Sample:print" %}" method="post">
    {% csrf_token %}
    <input type="text" placeholder="enter anything" id="TB_sample"/><br>
    <input type="submit" value="submit">
</form>

views.py

def print(request):
    value=request.POST['TB_sample']
    # value = request.REQUEST.get(request,'TB_sample')
    # value = request.POST.get('TB_sample','')
    print(value)
    return render(request , 'static/Sample/print.html',{"data":"I want to pass here 'Value'"})

I tried all commented types. still i get the many errors . None of these solutions working.

like image 649
deepak Avatar asked Feb 21 '17 05:02

deepak


2 Answers

Rename the print name of your function ( you called def print ). Never name a function of python builtin functions.

First, you have to give a name to input field to get the post parameter. Like,

<input type="text" placeholder="enter anything" name="TB_sample" id="TB_sample"/>

Then , you have typed

value=request.POST['TB_sample']

in django function.Which throws the MultiValueDictKeyError if there are no parameter named TB_sample.Always write,

value=request.POST.get('TB_sample')

which outputs None instead of throwing errors.

like image 186
Aniket Pawar Avatar answered Sep 24 '22 20:09

Aniket Pawar


Give 'name' to the input: <input name="firstname" type="text" value="firstname">

In django (views.py)

def register_form(request):
    if request.method =='POST':
        name = request.POST['firstname']
        print(name)

    return redirect('/')
like image 43
haxora Avatar answered Sep 20 '22 20:09

haxora