Django: AttributeError when I try to delete a user

2019-08-06 00:19发布

问题:

I've got a funny error when I try to delete a user from the admin pages (Django 1.5):

AttributeError at /admin/teaching/student/5/delete/

'tuple' object has no attribute 'replace'

followed by a long Traceback I don't understand, ending with a complaint about

line 43 in .../site-packages/django/utils/html.py in escape:
return mark_safe(force_text(text).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))

but text is just the string: Error in formatting: coercing to Unicode: need string or buffer, tuple found. So force_text is returning a tuple? What's that got to do with my models? I'm confused.

My users are students, and each Student model is has a OneToOneField with the User model, so I guess the corresponding Student object has to be deleted as well. I can delete the User from the shell with no problem at all (and the Student object disappears as well).

Edit: here's the Student model:

class Student(models.Model):
    user = models.OneToOneField(User)
    start_year = models.IntegerField()
    name = models.CharField(max_length=100)
    token = models.CharField(max_length=20, blank=True, null=True)

    def __unicode__(self):
        return self.name,

    def user_email(self):
        return self.user.email

回答1:

Spotted! If it's not a typo, the trailing comma in your __unicode__ return clause is making it return a tuple so that's the error you're getting.

def __unicode__(self):
    # note the tralining comma
    #return self.name,
    #should be like this (no comma)
    return self.name

Hope this works!