6

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.

Community
  • 1
  • 1
deepak
  • 176
  • 1
  • 2
  • 13

2 Answers2

12

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.

Aniket Pawar
  • 2,641
  • 19
  • 32
  • when i use value=request.POST.get('TB_sample') it raise **'str' object has no attribute 'POST'** – deepak Feb 21 '17 at 05:39
  • for value=request.POST['TB_sample'] it raise **MultiValueDictKeyError** after i tried ur solution – deepak Feb 21 '17 at 05:47
  • Man! you give your function name print !! Rename this print function to something else.Also see the edited answer. – Aniket Pawar Feb 21 '17 at 06:05
1

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('/')
haxora
  • 81
  • 6