我是django的新手,我正在创建一个简单的博客。我刚刚添加了标题',' body',' date'和'时间'领域。点击保存按钮后,该特定帖子已成功添加'但每个帖子的标题仍然是“邮件对象”。我尝试过“管理。制作”和#39;在manage.py sync之后管理和管理.py迁移命令,但它也没有帮助。
admin.py
from django.contrib import admin
from blog.models import Post
# Register your models here.
class PostAdmin(admin.ModelAdmin):
search_fields = ["title"]
admin.site.register(Post, PostAdmin)
models.py
from django.db import models
# Create your models here.
class Post(models.Model):
title=models.CharField(max_length = 140)
body=models.TextField()
date=models.DateTimeField()
def _unicode_(self):
return self.title
settings.py """
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mysite.db'
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
答案 0 :(得分:1)
您需要定义(重载)__unicode__(self)
方法(双_
)
回答有关python3的问题:
在Python 3上,因为所有字符串本身都被认为是Unicode,所以只能使用 str ()方法( unicode ()方法已过时)。
答案 1 :(得分:1)
你也可以使用__unicode__
(对于python2)或__str__
(对于python3)