Django: Context processor error for anonymous user - django

Hi I have a model which stores users actions. This model is used for showing notifications to logged in users.
Now the issue is code works fine with logged in users, however if I open homepage of application after logout, following error appears.
TypeError at /
'AnonymousUser' object is not iterable
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.10
Exception Type: TypeError
Exception Value:
**'AnonymousUser' object is not iterable**
Exception Location: /Library/Python/2.7/site-packages/django/utils/functional.py in inner, line 235
Python Executable: /usr/bin/python
Python Version: 2.7.10
I think the issue is because of template context processor I am using in my application.
Please help on this.
context code
from models import notifications
def activ_notification(request):
active = notifications.objects.filter(to_user=request.user,viewed=False)[:10]
return({'alert':active})
Settings
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
'task.notification.activ_notification',
],
},
},
]

Try just add is_authenticated check inside your view:
def activ_notification(request):
active = []
if request.user.is_authenticated():
active = notifications.objects.filter(to_user=request.user,viewed=False)[:10]
return({'alert':active})

Related

'AnonymousUser' object is not iterable error when using custom context processors

I am using a custom context processor in Django. But when the user is logged in it works file but when I try to login the user it throws 'AnonymousUser' object is not iterable
Here is the error:
TypeError at /
'AnonymousUser' object is not iterable
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1
Exception Type: TypeError
Exception Value: 'AnonymousUser' object is not iterable
And the context_processers file looks like
def noti_count(request):
count1 = Notification.objects.filter(user=request.user, seen=False)
count2 = Notification_general.objects.filter(seen=False)
return {"count1": count1, 'count2':count2,}
And the Context Processors Looks like
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'home.context_processors.noti_count',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Please help me out the code works fine for logged in user but when they they try to go to login page after the logout It throws me 'AnonymousUser' object is not iterable
Try it:
def noti_count(request):
if request.user:
count1 = Notification.objects.filter(user=request.user, seen=False)
....
What do you want to count?

Can I not use django.contrib.contenttypes?

I'm using django 3.0.
I use django-admin startproject mysite and created a sample django project.
I don't think the sample project has any models so I commented out "django.contrib.contenttypes" in INSTALLED_APPS in settings.py. I also commented out all middlewares.
I then wrote a simple view
from django.shortcuts import render
def index(request):
return render(request, 'hello.html')
and hello.html is just a blank file.
Once I access the page, django throws exception
Model class django.contrib.contenttypes.models.ContentType doesn't
declare an explicit app_label and isn't in an application in
INSTALLED_APPS.
Can anyone help explain the exception? The sample project doesn't have any model, why do I need django.contrib.contenttypes? Can django websites live without django.contrib.contenttypes?
I have to remove django.contrib.auth.context_processors.auth in TEMPLATES.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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',
# 'django.contrib.messages.context_processors.messages',
],
},
},
]

Setting up http error custom pages in django

I wanted to add custom error pages to my website, butI am getting the simple pages, for example the 403 error I am not getting the template I built. template is located in templates/http_errors/ folder.
my template settings in settings file looks like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [normpath(join(PROJECT_DIR, 'templates'))],
'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',
'django.template.context_processors.media',
'django.template.context_processors.i18n'
],
},
},
]
and urls.py:
from django.conf.urls import handler403
handler403 = 'core.views.custom_handler403'
and views.py:
def custom_handler403(request):
response = render_to_response('http_errors/HTTP403.html', {},
context_instance=RequestContext(request))
response.status_code = 403
return response
I tried a lot of options found on django docs and stackoverflow but could not still find the answer. It would be great if you helped me with this.
P.S. I am using Django 1.10 and Python 3.5
These custom pages will only work if you have DEBUG = False in your settings. Otherwise normal debug handlers will be used

Django TemplateDoesNotExist at /rango/

I've seen this question asked before, but I'm already using the newer TEMPLATES data structure which is the common solution.
From the tango with django book, I'm currently on unit 4. When I run my program with python manage.py runserver
I receive the following error:
TemplateDoesNotExist at /rango/
rango/index.html
Request Method: GET
Request URL: http://127.0.0.1:8000/rango/
Django Version: 1.5.1
Exception Type: TemplateDoesNotExist
Exception Value:
rango/index.html
Here is the relevant code in my ~/Workspace/wad2/tango_with_django_project/setings.py file:
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'tango_with_django_project', 'templates')
.
.
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',
],
},
},
]
.
.
Also, here is the relevant code in my ~/Workspace/wad2/rango/views.py file:
def index(request):
context_dict = {'boldmessage': "Crunchy, creamy, cookie, candy, cupcake!"}
return render(request, 'rango/index.html', context_dict)
Also, I cannot solve this problem with a direct path since I am trying to stick to the tutorial with dynamic pahs. Lastly, my template is located at ~/Workspace/wad2/tango_with_django_project/templates/rango/index.html
This was solved by updating my django version with:
pip install django==1.10.5

Django templates does not exist

So I work on windows and I try to load my websit home page. However I get the ''Templates doesnot exist '' errors I don't know why,
TemplateDoesNotExist at /
home/home.html
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.10.1
Exception Type: TemplateDoesNotExist
Exception Value:
home/home.html
Exception Location: C:\Python35\lib\site-packages\django\template\loader.py in get_template, line 25
Python Executable: C:\Python35\python.exe
Python Version: 3.5.2
Python Path:
Here is my Tracerback
you can see there that Django cannot even load some templates to be tested with. I'v seen others who have the same problem but at leat there was a list of tried template me I don't even have this.
here is my home/views.py
class IndexView(View):
template_name = 'home/home.html'
# not logged in
def get(self, request):
return render(request, self.template_name)
here is my templates variable in my setting.py
TEMPLATE = [
{
'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',
'django.contrib.messages.context_processors.messages',
],
},
},
]
in my code and my structure is
this and you can see that I added Home in the installed_app
yet after changing the path root of project, changing my python version (3.5 instead of 2.7) put a templates folder on the same level of my manage.py and change APPS_DIR to false i still get nothing. I have try to know if it was a path problem so I put the file in the root of project and test with isFile function of python and the return was true but if I try to render the page the same link I get the error.So I don't know if it's my code, my configuration of my project(virtual environnement, django etc) and It really gets annoying I use pycharm and I'm on windows 8.1
You could try with this path in settings.py to properly call the template:
'DIRS': [
os.path.join(PROJECT_ROOT, 'templates').replace('\\','/'),
],
You are not supposed to place your apps on an apps package. Try replacing your applications architecture to something like
INSTALLED_APPS = [
'applications.events',
'applications.student',
'applications.resume',
'applications.home`,
]
instead of "something.apps.somethingelse".
that is Pythonic.