JPC
JPC

Reputation: 5183

How to pass parameter from form post to view in Django - python ?

I'm new to Django and I am stuck at how can I use my html request form to show in view :

1. HTML form :

<form action="" method="post">
    <label for="your_name">Your name: </label>
    <input id="your_name" type="text" name="name" value="{{ name }}">
    <input type="submit" value="OK">
</form>

2. views/formout.py

def pageform(request):

    name = request.POST.get('name', '')

    return render(request, 'en/public/index.html',{name : "name"})

3. URL

url (r'^form$', 'jtest.views.formout'),

4. index.html

<p>
    name : {{name}}
</p>

Upvotes: 1

Views: 12751

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34593

First, you need to use an actual form class to sanitize and normalize any user-supplied values into their Python equivalent:

# forms.py

class NameForm(forms.Form):
    name = forms.CharField(max_length=255)

Second, you need to leverage the form in your view:

# views.py

from django.shortcuts import render
from your_app.forms import NameForm

def my_view(request):
    name_form = NameForm(request.POST or None, initial={'name': 'whatever'})

    if request.method == 'POST':
        if name_form.is_valid():
            # do something

    return render(request, 'name-form.html', {'name_form': name_form})

Lastly, your template needs to leverage the form:

# name-form.html

<form action="." method="post" enctype="application/x-www-form-urlencoded">
    {{ name_form.name.label_tag }}
    {{ name_form.name }}
    {{ name_form.name.errors }}
    <button type="submit">Submit</button>
</form>

By passing the initial value to the form class, Django will bind the value for you. If the form has errors, and name has a value, Django will re-bind the value submitted to that field from the request.POST dictionary.

Upvotes: 7

Related Questions