我正在尝试为Django视图编写一个自定义装饰器,该装饰器非常类似于login_required,只是在发现用户未登录时会执行其他操作。
最初,我将其放在与视图相同的目录中的custom.py文件中,但是每次尝试将其导入视图时,它都会返回“循环导入错误”。然后,我将其设为自己的文件夹,并返回相同的错误。作为最后的选择,我将其复制并粘贴到django.contrib.auth.decorators文件夹中。当我导入整个文件时,它没有返回循环导入错误,但是当我尝试调用装饰器时,它却返回了。为什么这样做呢?我检查了文件,确定没有进行循环导入。
错误:
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'mysite.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
查看导入:
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
import django.contrib.auth.decorators
装饰器:
def check_login(test_func):
def decorator(view_func):
@wraps(function)
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user.is_authenticated):
return view_func(request, *args, **kwargs)
else:
print("not written yet")
return _wrapped_view
return decorator