gpt4 book ai didi

python - Django - 'AnonymousUser' 对象不可迭代,因为我在上下文处理器中使用了用户过滤器

转载 作者:行者123 更新时间:2023-12-01 09:21:08 32 4
gpt4 key购买 nike

我使用context_processorts.py将某种过滤器传递到整个项目中,但它仅在用户登录时有效,当没有用户登录时它会返回错误。这是我的文件:

context_processors.py

def include_user_favs(request, user_favs=None):
if request.user.is_anonymous:
pass
else:
user_favs = Favorite.objects.filter(user=request.user)

context = {
'user_favs': user_favs,
}

return (context)

然后包含在settings.py中,例如:

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'fostania.context_processors.include_name_list',
'fostania.context_processors.include_current_user',
'fostania.context_processors.include_dress_need',
'fostania.context_processors.include_all_ads',
'fostania.context_processors.include_new_messages',
'fostania.context_processors.include_user_favs',
'django.contrib.messages.context_processors.messages',
],
},
},
]

这就是我在 HTML 中使用的方式

home.html

                               {% if user_favs %}
{% for item in user_favs %}
{% if item.item == dress %}
<a href="{% url 'favorite_item' dress.id %}">
<img src="{% static 'img/star-yes.png' %}" title="مسح من الفساتين المفضلة"></a>
{% else %}

<a href="{% url 'favorite_item' dress.id %}">
<img src="{% static 'img/star_no.png' %}" title="إضافة إلى الفساتين المفضلة"></a>

{% endif %}
{% endfor %}
{% else %}
<a href="{% url 'favorite_item' dress.id %}">
<img src="{% static 'img/star_no.png' %}" title="إضافة إلى الفساتين المفضلة"></a>
{% endif %}

这是错误和回溯:

“AnonymousUser”对象不可迭代

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 2.0.5
Python Version: 3.6.5
Installed Applications:
['django_filters',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'fostania_web_app.apps.FostaniaWebAppConfig']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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')



Traceback:

File "C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)

File "C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)

File "C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\python\Django\fostania\fostania_web_app\views.py" in home
17. user_favs = Favorite.objects.filter(user=request.user)

File "C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py" in filter
836. return self._filter_or_exclude(False, *args, **kwargs)

File "C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
854. clone.query.add_q(Q(*args, **kwargs))

File "C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py" in add_q
1253. clause, _ = self._add_q(q_object, self.used_aliases)

File "C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py" in _add_q
1277. split_subq=split_subq,

File "C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py" in build_filter
1187. self.check_related_objects(join_info.final_field, value, join_info.opts)

File "C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py" in check_related_objects
1052. for v in value:

File "C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py" in inner
216. return func(self._wrapped, *args)

Exception Type: TypeError at /
Exception Value: 'AnonymousUser' object is not iterable

最佳答案

您可以使用is_authenticated

Read-only始终为 True 的属性(与始终为 False 的 AnonymousUser.is_authenticated 相对)

def include_user_favs(request, user_favs=None):
if not request.user.is_authenticated:
user_favs = Favorite.objects.filter(user=request.user)

context = {
'user_favs': user_favs,
}

return (context)

关于python - Django - 'AnonymousUser' 对象不可迭代,因为我在上下文处理器中使用了用户过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50782897/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com