Django错误“ XXXForm”对象没有属性“ XXX”

时间:2018-06-22 07:59:24

标签: django django-forms

我使用Django构建了一个Web应用,提交表单时出现错误:

AttributeError at /CustomerInfo/
'CustomerForm' object has no attribute 'first_name'

项目名称为zqxt_views,应用名称为calc。 我在calc文件夹中创建了一个名为forms.py的文件,如下所示:
calc / forms.py:

from django import forms

class CustomerForm(forms.Form):
      customer_id = forms.IntegerField(label="Customer ID")
      first_name = forms.CharField(label="First Name", max_length=30)
      last_name = forms.CharField(label="Last Name", max_length=30)

calc / views.py:

# -*- coding: utf-8 -*-
#from __future__ import unicode_literals

#from django.shortcuts import render

from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
import MySQLdb
from calc.models import Customer
from calc.forms import CustomerForm
from django.db import connection

...

def show_save_customer(request):
    # if this is a POST request we need to process the form database
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = CustomerForm(request.POST)
        cursor = connection.cursor()
        query = """ insert into customers (first_name, last_name) values (%s, %s) """
        cursor.execute(query, [form.first_name, form.last_name])
        # check whether it's valid:
        if form.is_valid():
            #process the data
            return HttpResponseRedirect('AddressTableMaintain/');
    else:
        form = CustomerForm()

    return render(request, 'CustomerInfo.html', {'form': form})

# Create your views here.

如下所示的表单页面:
calc / templates / CustomerInfo.html:

{% extends 'base.html' %}

{% block title %} Add and Show Customer details {% endblock %}

{% block content %}
<style>
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
</style>
<form action="{% url 'show_save_customer' %}" method="post">
{% csrf_token %}
<table width="50%" align="center">
    <tr>
        <td>Customer ID</td>
        <td>
            {{ form.customer_id }}

        </td>
    </tr>
    <tr>
        <td>First Name</td>
        <td>
            {{ form.first_name }}

        </td>
    </tr>

    <tr>
        <td>Last Name</td>
        <td>
            {{ form.last_name }}
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center"><input type="submit" value = "OK" /></td>
    </tr>
</table>
</form>
{% endblock %}

我填写了一些数据并单击“确定”按钮后,总是出现开头提到的错误,有人可以告诉我我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:2)

实际上,表单不会将其字段公开为属性。您需要通过form.cleaned_data访问数据-在调用form.is_valid() 应该这样做。

    form = CustomerForm(request.POST)
    cursor = connection.cursor()
    # check whether it's valid:
    if form.is_valid():
        query = """ insert into customers (first_name, last_name) values (%s, %s) """
        cursor.execute(query, [form.cleaned_data['first_name'], form.cleaned_data['last_name']])
        return HttpResponseRedirect('AddressTableMaintain/');

但是也请注意,除非您有充分的理由,否则应避免使用原始SQL查询,并使用Django模型层进行查询。在这种情况下,ModelForm会更加适合,因为它可以通过简单的form.save()为您创建并保存实例。

还请注意,您在表单上执行任何操作以在表单无效时显示错误。这样做的方法有很多种,但至少应将{{ form.errors }}放在某个地方。