`__unicode __()`在Django教程中的基本轮询应用程序中不能使用 [英] `__unicode__()` addition not working in basic poll application in Django tutorial

查看:115
本文介绍了`__unicode __()`在Django教程中的基本轮询应用程序中不能使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Django开发Django开发源代码和源代码所需的一切,我正在通过Django教程。我试图用python3做任何事情,而不是Ubuntu 12.10上的python。



一切似乎都很顺利,直到教程中我们应该重新定义 __ unicode __()为了在从表中请求object.all()时返回一个明智的结果。它根本不起作用我决定尝试 __ str __(),它的工作!



但是,本教程解释我们不是重新定义 __ str __()。那么我的安装有什么问题, __ unicode __() __ str __()中不起作用?

解决方案

Python 3 vs 2中的字符串处理方式不同



在2, __ str __()返回的字节,而 __ unicode __()返回的字符。在3中, __ str __()现在返回字符,因为字符串现在是本机unicode,而 __ unicode __()不存在。如果你真的需要 __ str __()的旧2行为,我相信现在是 __ bytes __()。 p>

简单的答案,坚持使用 __ str __()如果您使用的是Python 3,并意识到Django教程明确说明是为2.x写的,所以会有差异。


I'm working through the Django tutorial after having installed the development source of Django along with PostgreSQL from source and everything else needed from source. I'm trying to do everything with python3 instead of python on Ubuntu 12.10.

Everything seemed to be going well until I got to the part in the tutorial where we're supposed to redefine __unicode__() in order to return a sensible result when we ask for objects.all() from a table. It's not working at all. I decided to try __str__(), and it worked!

But, the tutorial explains we're not supposed to redefine __str__(). So, what's wrong with my install that __unicode__() doesn't work while __str__() does? Other methods from the tutorial work fine.

解决方案

Strings are handled differently in Python 3 vs 2.

In 2, __str__() returned bytes, while __unicode__() returned characters. In 3, __str__() now returns characters, as strings are now natively unicode, and __unicode__() doesn't exist. If you really need the old 2 behavior for __str__(), I believe it is now __bytes__().

Short answer, stick with __str__() if you are using Python 3, and realize that the Django tutorials explicitly state they are written for 2.x, so there will be differences.

这篇关于`__unicode __()`在Django教程中的基本轮询应用程序中不能使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆