简体   繁体   English

如何在Django-python中从表单发布传递参数以进行查看?

[英]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 : 我是Django的新手,我被困在如何使用html请求表单在view中显示:

1. HTML form : 1. HTML表单:

<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 2. views / formout.py

def pageform(request):

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

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

3. URL 3.网址

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

4. index.html 4. index.html

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

First, you need to use an actual form class to sanitize and normalize any user-supplied values into their Python equivalent: 首先,您需要使用实际的表单类将用户提供的值清理并归一化为它们的Python等效项:

# 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. 通过将初始值传递给表单类,Django将为您绑定该值。 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. 如果表单有错误,并且name具有值,Django将重新绑定从request.POST字典提交到该字段的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM