在针对已定义的 url 提交带有操作 post 的表单时,请求显示为空

On submitting form with action post on a defined url, request is showing empty

request.POST 显示为空。 因此表单永远不会被验证。 我需要通过 ajax 电话来完成吗?

这是 html 和视图 HTML:

    <form action="{% url 'customer_form' %}" method="post">
        {% csrf_token %}
        <label for="first_name">First Name</label>
        <input id="first_name" type="text">
        <label for="last_name">Last Name</label>
        <input id="last_name" type="text">
        <label for="email">Email</label>
        <input id="email" type="email">
        <label for="address">Address</label>
        <textarea id="address"></textarea>
        <input type="submit" value="Save">
    </form>

查看:

    def customer_form(request):
    if request.method == 'POST':
        form = CustomerForm(request.POST)
        if form.is_valid():
            fname = form.cleaned_data['first_name']
            lname = form.cleaned_data['last_name']
            email = form.cleaned_data['email']
            address = form.cleaned_data['address']
            Customer.objects.create(
                first_name=fname,
                last_name=lname,
                email=email,
                address=address
            )
            return HttpResponse('Customer Saved')
        else:
            return HttpResponse('Not saved')
    else:
        return render(request, 'customer/customer.html')

网址:

    urlpatterns = [
        url(r'^customer_form/', 
        views.customer_form,name='customer_form'),
        ]

您还没有为您的任何输入提供 name 属性,因此不会提交任何数据。

但是你应该使用 Django 形式来输出它们,无论如何:

{{ form.first_name }}

等等

扩展 @Daniel's 答案,每个表单输入元素都必须定义一个 name 属性, 否则该元素将不会被处理。

根据W3C form specification

用户通过named controls.

与表单交互

在其规范中,它提到下面的 control 是有效的,以便在另一端接收该字段。

A successful control is "valid" for submission. Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.

因此,元素必须定义一个控件名称才能有效,这意味着我们需要为表单中的输入类型提供 name 属性才能正常工作。

A control's "control name" is given by its name attribute.

你可以这样做:

<form action="{% url 'customer_form' %}" method="post">
    {% csrf_token %}
    <label for="first_name">First Name</label>
    <input id="first_name" name="first_name" type="text">
    <label for="last_name">Last Name</label>
    <input id="last_name" name="last_name" type="text">
    ...
</form>

您也可以使用 {{form.first_name}},Django 会自动将 first_name 呈现为输入文本字段。