'联系'对象没有属性' first_name'

时间:2014-04-27 08:56:05

标签: python django

我的代码:

from django.db import models
from django.db import connection

class Contact(models.Model):

#Retrieving data from a database
    # #Create the cursor
    cursor = connection.cursor()
    #Write the SQL code
    sql_string = 'SELECT * FROM contacts_contact'
    #Execute the SQL
    cursor.execute(sql_string)

    #Print more than two: for row in cursor.fetchall: print(row[1])
    #Print one record
    print("\033[92m View a sample record: \033[93m" + cursor.fetchone()[1] + "\033[0m")


    def form():
        first_name = models.CharField(
            max_length = 255,
        )
        last_name = models.CharField(
            max_length = 255,
        )
        email = models.EmailField()
        file = models.FileField(upload_to='files/')

    form()

    def __str__(self):
        return ' '.join([
            self.first_name,
            self.last_name,
        ])

我的错误:'联系'对象没有属性' first_name'

如果"的代码形成"别的女士,那就没事了。

请帮忙

2 个答案:

答案 0 :(得分:1)

遗憾的是,整个代码完全是胡说八道。你需要回去做教程:你在这里做的事情没有意义。你不需要SQL命令;如果你这样做,你就不会在课堂上做这些; 需要将字段定义放在类级别而不是奇怪命名的form方法中;你不应该在课堂上定义方法后立即调用方法;等等。

答案 1 :(得分:0)

为什么函数form中的局部变量会变成神奇的类属性?

from django.db import models
from django.db import connection

class Contact(models.Model):
    first_name = models.CharField(
        max_length = 255,
    )
    last_name = models.CharField(
        max_length = 255,
    )
    email = models.EmailField()
    file = models.FileField(upload_to='files/')

    def __str__(self):
        return '%s %s' % (
            self.first_name,
            self.last_name,
        )

类仅用于定义,不用于执行代码。