Django 1.11:模板渲染期间出错,__str__返回非字符串(类型NoneType)

时间:2018-07-15 23:36:33

标签: python django django-templates

Django版本:1.11 Python版本:3.5我正在尝试遵循Django教程,但有一个我无法解决的问题,我无法删除此错误

异常类型:/ posts / new /

处的TypeError

异常值:__ str__返回了非字符串(类型NoneType)

enter image description here

回溯

enter code here
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models

import misaka

from groups.models import  Group

from django.contrib.auth import get_user_model
User = get_user_model()


class Post(models.Model):
    user = models.ForeignKey(User, related_name="posts")
    created_at = models.DateTimeField(auto_now=True)
    message = models.TextField()
    message_html = models.TextField(editable=False)
    group = models.ForeignKey(Group,  
    related_name="posts",null=True,blank=True)

    def __str__(self):
        return self.message

    def save(self, *args, **kwargs):
        self.message_html = misaka.html(self.message)
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse(
             "posts:single",
              kwargs={
                 "username": self.user.username,
                 "pk": self.pk
                      }
                    )

    class Meta:
         ordering = ["-created_at"]
         unique_together = ["user", "message"]

这是我的 models.py文件

from django.conf.urls import url

from . import views

app_name='posts'

urlpatterns = [
    url(r"^$", views.PostList.as_view(), name="all"),
    url(r"new/$", views.CreatePost.as_view(), name="create"),
    url(r"by/(?P<username>[-\w]+)/$"
           ,views.UserPosts.as_view(),name="for_user"),
    url(r"by/(?P<username>[-\w]+)/(?P<pk>\d+)/$"
            ,views.PostDetail.as_view(),name="single"),
    url(r"delete/(?P<pk>\d+)/$",views.DeletePost.as_view(),name="delete"),
    ]

这就是我的 urls.py 帖子申请

enter code here

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')

SECRET_KEY = '(5qpl&b-b48^jszl@nz02#lgbw%tp(o)_wb!)b&k(j9*kueh@&'

DEBUG = True

ALLOWED_HOSTS = []
INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'django.contrib.humanize',
   'bootstrap3',
   'accounts',
   'groups',
   'posts',
    ]

MIDDLEWARE = [
   'django.middleware.security.SecurityMiddleware',
   'django.contrib.sessions.middleware.SessionMiddleware',
   'django.middleware.common.CommonMiddleware',
   'django.middleware.csrf.CsrfViewMiddleware',
   'django.contrib.auth.middleware.AuthenticationMiddleware',
   'django.contrib.messages.middleware.MessageMiddleware',
   'django.middleware.clickjacking.XFrameOptionsMiddleware',
      ]

ROOT_URLCONF = 'simplesocial.urls'

TEMPLATES = [
 {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [TEMPLATE_DIR,],
    '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 = 'simplesocial.wsgi.application'
DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
  }

AUTH_PASSWORD_VALIDATORS = [
  {
    'NAME':
      'django.contrib.auth.password_validation.
        UserAttributeSimilarityValidator',
        },
         {
    'NAME': 'django.contrib.auth.password_validation.
       MinimumLengthValidator',
         },
        {
    'NAME': 'django.contrib.auth.password_validation.
          CommonPasswordValidator',
         },
          {
    'NAME': 'django.contrib.auth.password_validation.
          NumericPasswordValidator',
          },
          ]
enter code here

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

LOGIN_REDIRECT_URL = "test"
LOGOUT_REDIRECT_URL = "thanks"

settings.py

<section style="box-sizing: border-box;"><section style="display: inline-block; vertical-align: middle; width: 50%; box-sizing: border-box; background: red; height: 30px;"></section><section style="display: inline-block; vertical-align: middle; width: 50%; box-sizing: border-box; background: blue; height: 30px;"></section></section>

我用google搜索,但没找到

1 个答案:

答案 0 :(得分:0)

我知道有点晚了,但是在添加新帖子的同时执行相同的项目时遇到了相同的错误。我发现问题出在Group模型中。请检查您的Group模型,然后在 str中放入return 功能。