django - 'NoneType' 对象在 Django 项目中不可迭代

标签 django nonetype

当我尝试使用“python manage.py runserver ip:port”运行我的 django 应用程序时出现“‘NoneType’对象不可迭代”错误,而如果我使用“python manage.py runserver 0.0.0.0”则不会发生相同的错误。 0.0:8000"。我真的需要使用我的 IP 地址来完成这项工作。
Link to the error page 1
Link to the error page 2

我究竟做错了什么?

这是我的 settings.py 的样子:

"""
Django settings for SimStudent project.

Generated by 'django-admin startproject' using Django 2.2.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

#ALLOWED_HOSTS = ['0.0.0.0', '10.153.1.51', '127.0.0.1']
ALLOWED_HOSTS = ['*']



# Application definition

INSTALLED_APPS = [
    'channels',
    'chat',
    'django_tables2',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'SimStudent'

]

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 = 'SimStudent.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'SimStudent.context_processor.tutor_tutee_session_info',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'SimStudent.wsgi.application'

ASGI_APPLICATION = 'SimStudent.routing.application'

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    #'default': {
    #    'ENGINE': 'django.db.backends.sqlite3',
    #    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    #}

    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'simstudent_oz',
        'USER': 'sim_tasmia',
        'PASSWORD': '123456',
        'HOST': 'localhost',
        'PORT': '5433',
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

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',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/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/2.2/howto/static-files/

STATIC_URL = '/static/'
#STATIC_ROOT = os.path.join(BASE_DIR, "static/")
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]


我的 context_processor.py 看起来像:

from django.shortcuts import get_object_or_404
from django.utils.safestring import mark_safe
import json
from chat.models import Session, TutorTuteeConversation
from django.core import serializers

from chat.models import Session


def tutor_tutee_session_info(request):
    if 'session_id' in request.session:
        session_id = request.session['session_id']
        room_name = request.session['room_name']
        print("inside context", session_id)
        session = get_object_or_404(Session, pk=int(session_id))
        chat_history = TutorTuteeConversation.objects.filter(session_id=int(session_id)).order_by('comment_time')
        dict_chat_history = serializers.serialize("json", chat_history)
        print("dict chat history inside context", dict_chat_history)
        return {
            "session_info": session,
            "chat_history": mark_safe(json.dumps(dict_chat_history)),
            "room_name": room_name,
        }


Project directory structure is here

最佳答案

它发生在我身上,并通过使 else 返回一个空字典来解决,例如:

def test(request):
   if condition:
      return {"val":val}
   else:
      return {}

关于django - 'NoneType' 对象在 Django 项目中不可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59075266/

相关文章:

python-3.x - 属性错误 : 'NoneType' object has no attribute 'astype'

python-2.7 - 检查 Python 字典中的所有值时的意外结果为 None

python - 全局变量是 None 而不是实例 - Python

python - 如何使用基于 Web 应用程序的身份验证在 Python Django 中使用 Microsoft graph api (python-o365) 发送和读取邮件?

python - ImportError:无法导入名称信号

python - 使用 Django 和 matplotlib 进行动态绘图

Django 测试在 postgres hstore 迁移时失败

Django - 无法获取 Highcharts 来显示数据

python - NoneType 对象没有属性 endwith (Tensorflow)

python - None 真的是内置的吗?