QueryDict中的Django Post Request中没有返回任何值

时间:2019-01-23 14:42:54

标签: python django python-3.x

我正在尝试学习Django,却找不到任何解决方案。我运行一个提交按钮以收集全名,但是当我单击“提交”时,它将显示“无”作为值。我不明白我在做什么错。它缺少csrf令牌,但我添加了它,但仍然没有返回。

My Result for QueryDict

view.html

       <div class='containter'>
        <div class='row'>
            <div class='col'>
                <p>{{ content }}</p>
<div class='col-sm-6 col-12'>

<form method="POST"> {% csrf_token %}
    <input type='text' class='form-control' placeholder="Name" value='fullname'>
    <button type='submit' class='btn btn-default'>Submit</button>

</form>
</div>
            </div>
        </div>
    </div>
    </div>

views.py

    from django.shortcuts import render
from django.http import HttpResponse

def home_page(request):
    context = {
        "title": "Homepage",
        "content": "Welcome to the Homepage"
    }
    return render(request, "home_page.html", context)

def about_page(request):
    context = {
        "title": "About Page",
        "content": "Welcome to the About Page"
        }
    return render(request, "home_page.html", context)

def contact_page(request):
    context = {
        "title": "Contact Us",
        "content": "Welcome to the Contact Page"
        }
    if request.method == "POST":
        print(request.POST)
        print(request.POST.get('fullname'))
    return render(request, "contact/view.html", context)

urls.py

from django.conf.urls import url
from django.contrib import admin
from .views import home_page, about_page, contact_page

urlpatterns = [
    url(r'^$', home_page),
    url(r'^about/$', about_page),
    url(r'^contact/$', contact_page),
    url(r'^admin/', admin.site.urls),

2 个答案:

答案 0 :(得分:1)

您的代码中存在的问题是,您没有发送名为“全名”的输入,而是实际上发送的是不带名称的输入,其值为“ fullname”。

您必须更新HTML并在输入标签中设置名称atribbute:

<input type='text' name='fullname' value='what ever you need to get in backend'>

因此,在后端,您可以获取输入的值:

request.POST.get('fullname')

这将获得下一个字符串:what ever you need to get in backend

答案 1 :(得分:0)

<input type='text' class='form-control' placeholder="Name" value='fullname'>

应该类似于

<input type='text' class='form-control'  name="fullname" placeholder="Name" value='fullname'>