在django的中间件中安全地导入模型

时间:2018-05-17 12:57:35

标签: django

我一直在尝试在中间件处理函数中导入模型,但是我收到了错误:
Value: Model class x doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS

我猜测问题是应用程序设置不完整,但是,我所有解决这个问题的尝试都遇到了障碍。

middleware.py函数

from notifications.models import Notification
    ...

class CheckNotificationMiddleware(object):

    """
    Checks clicked notification to mark it as read
    """
    def process_request(self, request):
        if request.user.is_authenticated():

            notification_id = request.GET.get('notification_id')
            if notification_id:
                AppConfig.get_model('Notification')
                try:

                    notification = Notification.objects.get(
                        pk=notification_id, status=0, recipient=request.user)
                    notification.status = 1
                    notification.save()
                except ObjectDoesNotExist:
                    pass

settings.py

INSTALLED_APPS = (
...
    'notifications',
...
)

我尝试了几件事,包括......

from django.apps import AppConfig
AppConfig.get_model('Notification')

我正在使用Django版本1.11和python 2.7

1 个答案:

答案 0 :(得分:0)

您必须在{p>下包含notifications

INSTALLED_APPS = [
'notifications',
]

在设置文件中