I'm working on only my second tutorial for creating a Django project and app. The first tutorial I completed was on djangoproject.com and I created the ever popular "Polls" app. That first tutorial specified that "it’s important to add __str__()
methods to your models", but it also stated that "on Python 2, you should define __unicode__()
methods returning unicode values instead." I'm running Python 2.7.9, and I successfully used __unicode__()
in that first tutorial. I'm having trouble with the string formatting in the second tutorial that I'm currently working on, which is at effectivedjango.com.
我正在研究创建Django项目和应用程序的第二个教程。我完成的第一个教程是在djangoproject.com上,我创建了流行的“民意调查”应用程序。这第一个教程规定:“它添加__str __()方法,以你的模型是非常重要的”,但同时也指出,“在Python 2中,你应该定义__unicode __()返回Unicode值,而不是方法。”我正在运行Python 2.7.9,并且我在第一个教程中成功使用了__unicode __()。我在目前正在进行的第二个教程中遇到字符串格式化问题,这是在effectivedjango.com上。
Here is what worked for the first tutorial:
以下是第一个教程的作用:
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return u'%s' % self.question_text
And here is what I've unsuccessfully tried for the second tutorial:
以下是我在第二个教程中尝试失败的原因:
class Contact(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.EmailField()
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
I've also tried return u'%s' + ' ' + '%s' % (self.first_name, self.last_name)
, and return u'%s' + u' ' + u'%s' % (self.first_name, self.last_name)
.
我也试过回复你'%s'+''+'%s'%(self.first_name,self.last_name),并返回你'%s'+ u''+ u'%s'%(自我.first_name,self.last_name)。
When I try to create a Question
object in my database using any of the above attempts, I keep getting TypeError: not all arguments converted during string formatting
. What am I doing wrong with the string formatting? I'm very new to Python, and coding period (in case you couldn't tell), so please "talk slowly and clearly" and "go easy on me" when giving any answers. Thanks!
当我尝试使用上述任何尝试在我的数据库中创建一个Question对象时,我不断收到TypeError:并不是在字符串格式化过程中转换了所有参数。我在字符串格式化方面做错了什么?我是Python的新手,也是编码时期(如果你不知道的话),所以在给出任何答案时请“慢慢地,清楚地说话”和“轻松对待我”。谢谢!
1 个解决方案
#1
Hmm. This seems to look correctly. Is it possible that you have some Contact()-entries stored in your database which don't contain a first_name or
嗯。这似乎看起来正确。是否有可能存在一些Contact() - 数据库中存储的条目,其中不包含first_name或
#1
Hmm. This seems to look correctly. Is it possible that you have some Contact()-entries stored in your database which don't contain a first_name or
嗯。这似乎看起来正确。是否有可能存在一些Contact() - 数据库中存储的条目,其中不包含first_name或