user763410
user763410

Reputation: 562

Django/Python: Single quotes causing Django admin interface to throw error

I am new to django and am writing a twitter clone to learn it.

I have a model like the following

class message(models.Model):
    text = models.TextField()
    date_n_time = models.DateTimeField(default=datetime.now, null=True,blank=True)
    parent_2 = models.ForeignKey('self',null=True,blank=True)    
    def __unicode__(self):
        return str(self.id)+"_"+self.text+"_"+str(self.date_n_time)+"_"+"___"+str(self.parent_2)

Now, I added a message with text equal to following (quotes are part of what I entered through Django create form.

'prod'

I am trying to access the message object through admin interface: 127.0.0.1:8000/admin/core/message/

I get the following error message in

'ascii' codec can't decode byte 0xe2 in position 9: ordinal not in range(128). You passed in message: [Bad Unicode data] (class 'core.models.message')

Other stack overflow answers seem to suggest this is unicode issue, but if I change test to

"prod"

I do not get any errors.

Why am I getting the error only with single quotes? How do I catch this problem through django forms/model code, preferably at the time of saving the input form?

Upvotes: 0

Views: 574

Answers (2)

jape
jape

Reputation: 2901

I would try changing your unicode to the following:

def __unicode__(self):
    return u'{}"_"{}"_"{}"_""__"{}'.format(self.id, self.text, self.date_n_time, self.parent_2)

That should return what you initially wanted, including the quotes. I would also consider combining the portion that has "_""__" to just "___". There's no real reason to separate the underscores if they're going to be following each other.

If you don't want the quotes, simply delete them. Keep the {}. It's a more reliable format compared to "%s" % (context)

Good luck with your clone!

Upvotes: 3

Wannabe Coder
Wannabe Coder

Reputation: 1497

Are you using Python2.7 or Python3? If you are using Python2.7, use __unicode__(), otherwise, use __str__().

Please take a look at the "__str__ or __unicode__?" section of this link. For proper usage, please take a look at the docs for __unicode__() and __str__().

EDIT:
I cannot replicate your error. I can access the admin just fine. By any chance, are you using an older version of Django (older than 1.8)? Test

Try using this instead since this is supposedly the proper way to handle unicode strings as endorsed by the Django docs.

def __unicode__(self):
    return u'%s_%s_%s___%s' % (self.id, self.text, self.date_n_time, self.parent_2)

Upvotes: 2

Related Questions