【问题标题】:Adding a new record in Django Admin gives persistent error在 Django Admin 中添加新记录会导致持续错误
【发布时间】:2013-05-14 14:18:38
【问题描述】:

我刚刚开始搞乱 Django。我创建了一个新项目和一个新应用程序。在那个应用程序中,我创建了一个模型并激活了管理员。这似乎工作正常。然后我想使用管理员向数据库添加一些新记录。在前三个表中一切正常,但在第四个表(称为“locations”)中,我收到此错误消息:'tuple' object has no attribute 'encode' .完整的错误在 pastebin 上:http://pastebin.com/WjZat6NN

奇怪的是,当我现在返回常规管理页面并想要单击刚刚出现错误的表时,我也收到了错误(因此无需尝试添加任何内容)。

我的问题:为什么会这样?可能我的models.py有问题,所以我也把它贴在了这条消息的下面。

欢迎所有提示!

from django.db import models

# Create your models here.
class countries(models.Model):
    country = models.CharField(max_length=100)
    def __unicode__(self):
        return self.country

class organisationTypes(models.Model):
    organisationType = models.CharField(max_length=100)
    def __unicode__(self):
        return self.organisationType

class organisations(models.Model):
    organisationName = models.CharField(max_length=200)
    organisationType = models.ForeignKey(organisationTypes)
    countryofOrigin = models.ForeignKey(countries)
    def __unicode__(self):
        return self.organisationName

class locations(models.Model):
    organisation = models.ForeignKey(organisations)
    countryofLocation = models.ForeignKey(countries)
    telNr = models.CharField(max_length=15)
    address = models.CharField(max_length=100)
    def __unicode__(self):
        return self.organisation, self.countryofLocation, self.telNr, self.address

【问题讨论】:

  • 只是一个注释。您应该遵循标准命名约定。类名像大多数语言一样大写,类属性和变量用下划线 ('_') 分隔。不是你正在使用的骆驼箱。

标签: python django django-admin


【解决方案1】:

这里:

def __unicode__(self):
        return self.organisation, self.countryofLocation, self.telNr, self.address

你正在返回一个元组。它需要一个字符串。

把它改成这样:

def __unicode__(self):
        return "%s - %s - %s - %s" % (self.organisation self.countryofLocation, self.telNr, self.address)

【讨论】:

    【解决方案2】:

    问题很可能出在这一行...

    return self.organisation, self.countryofLocation, self.telNr, self.address
    

    ...您从 __unicode__ 方法返回一个元组。您需要返回一个字符串对象,尽管不清楚它应该是什么。或许……

    return ', '.join((self.organisation, self.countryofLocation, self.telNr, self.address))
    

    ...?

    【讨论】:

      【解决方案3】:

      您只能返回一个字符串作为模型实例的代表。

      所以更好用

      return self.organisation + '-'+ self.countryofLocation + '-'+self.telNr+'-'+self.address
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-02
        • 1970-01-01
        • 2014-06-17
        • 2021-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多