我正在django構建應用程序,並且我在HEROKU上部署了此應用程序。我的錯誤是我在我的模型中有「名稱」作爲外鍵,當我在我的應用程序上訪問部署在heroku名稱上的名稱顯示爲「用戶對象」時。獲取用戶對象名稱
我能夠在本地服務器上運行時訪問正確的名稱。
我已經嘗試了許多不同的方法,但仍然無法修復它。
圖片更好地理解我的錯誤。
我正在django構建應用程序,並且我在HEROKU上部署了此應用程序。我的錯誤是我在我的模型中有「名稱」作爲外鍵,當我在我的應用程序上訪問部署在heroku名稱上的名稱顯示爲「用戶對象」時。獲取用戶對象名稱
我能夠在本地服務器上運行時訪問正確的名稱。
我已經嘗試了許多不同的方法,但仍然無法修復它。
圖片更好地理解我的錯誤。
的問題是在Upload.__unicode__
方法。在本地你有Python2.7
因此做unicode(self.name)
返回對象的適當表示。雖然在Heroku上,你有Python3.6.1
它期望您提供__str__
因此你需要實現__str__
以及兼容性:
class Upload(models.Modal):
# other fields
def __unicode__(self):
retrun unicode(self.name)
def __str__(self):
return self.__unicode__().encode('utf-8')
或者乾脆使用python_2_unicode_compatible只有__str__
實現:在模板否則
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Upload(models.Modal):
# other fields
def __str__(self):
retrun str(self.name)
你可以簡單地使用{{ i.name.username }}
來獲取用戶名。
是啊謝謝你的幫助。 –
沒問題,我用'python_2_unicode_compatible'修飾器添加了更簡單的方法來檢查它。 –
更好的是,在開發和生產之間使用相同版本的Python。 –
對於實施例
Class User(models.Model):
@property
def get_fullname(self):
return self.first_name + ' ' + self.last_name
在模板{{i.name.get_fullname}}
我想它是一個Python版本的衝突。什麼是你的本地python版本和heroku python版本? –
@AamirAdnan我在我的系統(本地)上使用Python 2.7,並且heroku使用的是 python-3.6.1 –
無論這是您的問題的來源,在服務器上使用Python 2似乎是一個好主意,重新使用Python 2開發:https://devcenter.heroku.com/articles/python-runtimes –