django, gravatar - add_to_builtins('gravatar.gravatar') causes crash on page load - django

add_to_builtins('gravatar.gravatar')
is being used in my settings.py file, and it causes a crash on page load with this error:
Traceback (most recent call last):
File "C:\development\python\Lib\site-packages\django\core\servers\basehttp.py", line 283, in run
self.result = application(self.environ, self.start_response)
File "C:\development\python\Lib\site-packages\django\contrib\staticfiles\handlers.py", line 68, in call
return self.application(environ, start_response)
File "C:\development\python\Lib\site-packages\django\core\handlers\wsgi.py", line 272, in call
response = self.get_response(request)
File "C:\development\python\Lib\site-packages\django\core\handlers\base.py", line 169, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "C:\development\python\Lib\site-packages\django\core\handlers\base.py", line 203, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "C:\development\python\Lib\site-packages\django\views\debug.py", line 59, in technical_500_response
html = reporter.get_traceback_html()
File "C:\development\python\Lib\site-packages\django\views\debug.py", line 128, in get_traceback_html
t = Template(TECHNICAL_500_TEMPLATE, name='Technical 500 template')
File "C:\development\python\Lib\site-packages\django\template\base.py", line 108, in init
self.nodelist = compile_string(template_string, origin)
File "C:\development\python\Lib\site-packages\django\template\base.py", line 135, in compile_string
parser = parser_class(lexer.tokenize())
File "C:\development\python\Lib\site-packages\django\template\debug.py", line 34, in init
super(DebugParser, self).init(lexer)
File "C:\development\python\Lib\site-packages\django\template\base.py", line 208, in init
print lib.tags
AttributeError: 'NoneType' object has no attribute 'tags'
If i don't have any issue with using gravatar if i don't use the add_to_builtins functionality - that is, with plain old load tags in my views. I'm just using it a fair bit, so thought i might make use of the add_to_builtins functionality.
From the looks of things, the imported version crashes because the import_library(module) for gravatar.gravatar returns None (i know this because i printed out that line, and it returns None) - what is wrong with what i've done?

oh gravatar.
Ok, so i was all wrong in how to import this using the add_to_builtins - what i needed to do was:
add_to_builtins('gravatar.templatetags.gravatar')
i'm unsure as to why, but that works a treat. Now i don't need to have any messy "load" statements, and i can happily call
{% gravatar story.user 40 %}
from any of my templates. yay!

Related

testdriven.io: The Definitive Guide to Celery and Django. Running task from Django shell causes error

I am currently going through 'The Definitive Guide to Celery and Django' course by testdriven.io. I've managed to containerize the whole application. Everything was built correctly and seemed to work just fine, but when I tried to enter the Django shell and run a task, to ensure everything works correctly, the following error appeared.
>>> divide.delay(1, 2)
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/kombu/utils/functional.py", line 30, in __call__
return self.__value__
AttributeError: 'ChannelPromise' object has no attribute '__value__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errors
yield
File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 433, in _ensure_connection
return retry_over_time(
File "/usr/local/lib/python3.10/site-packages/kombu/utils/functional.py", line 312, in retry_over_time
return fun(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 877, in _connection_factory
self._connection = self._establish_connection()
File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 812, in _establish_connection
conn = self.transport.establish_connection()
File "/usr/local/lib/python3.10/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection
conn.connect()
File "/usr/local/lib/python3.10/site-packages/amqp/connection.py", line 323, in connect
self.transport.connect()
File "/usr/local/lib/python3.10/site-packages/amqp/transport.py", line 129, in connect
self._connect(self.host, self.port, self.connect_timeout)
File "/usr/local/lib/python3.10/site-packages/amqp/transport.py", line 184, in _connect
self.sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python3.10/site-packages/celery/app/task.py", line 425, in delay
return self.apply_async(args, kwargs)
File "/usr/local/lib/python3.10/site-packages/celery/app/task.py", line 575, in apply_async
return app.send_task(
File "/usr/local/lib/python3.10/site-packages/celery/app/base.py", line 788, in send_task
amqp.send_task_message(P, name, message, **options)
File "/usr/local/lib/python3.10/site-packages/celery/app/amqp.py", line 510, in send_task_message
ret = producer.publish(
File "/usr/local/lib/python3.10/site-packages/kombu/messaging.py", line 177, in publish
return _publish(
File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 523, in _ensured
return fun(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/kombu/messaging.py", line 186, in _publish
channel = self.channel
File "/usr/local/lib/python3.10/site-packages/kombu/messaging.py", line 209, in _get_channel
channel = self._channel = channel()
File "/usr/local/lib/python3.10/site-packages/kombu/utils/functional.py", line 32, in __call__
value = self.__value__ = self.__contract__()
File "/usr/local/lib/python3.10/site-packages/kombu/messaging.py", line 225, in <lambda>
channel = ChannelPromise(lambda: connection.default_channel)
File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 895, in default_channel
self._ensure_connection(**conn_opts)
File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 432, in _ensure_connection
with ctx():
File "/usr/local/lib/python3.10/contextlib.py", line 153, in __exit__
self.gen.throw(typ, value, traceback)
File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 450, in _reraise_as_library_errors
raise ConnectionError(str(exc)) from exc
kombu.exceptions.OperationalError: [Errno 111] Connection refused
I've done a quick research and in most cases it seemed to be a lack of the following lines
from config.celery import app as celery_app
__all__ = ['celery_app']
in the config.__init__.py, but it's clearly not an issue here.
I also double checked whether redis container is up and listening on port 6379.
The only difference between my code and the course code is that I decided to use Poetry package manager instead of requirements.txt file and pip.
At this point I am a little bit confused I'll be thankful for any tip. You can find the whole code below:
https://github.com/Kibraks/django-celery-app

Trying to run a basic django code. When I run 'python manage.py runserver', I get this:

Just created a project, added app definition in settings.py, and created an app with a urls.py file seperately and tried to include the urls.py file in the main urls.py file that is created by default when we create a project and tried to return a HttpResponse in a seprate file.
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\Sujit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 591, in url_patterns
iter(patterns)
TypeError: 'module' object is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Sujit\AppData\Local\Programs\Python\Python39\lib\threading.py", line 950, in _bootstrap_inner
self.run()
File "C:\Users\Sujit\AppData\Local\Programs\Python\Python39\lib\threading.py", line 888, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Sujit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\Sujit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Sujit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 392, in check
all_issues = checks.run_checks(
File "C:\Users\Sujit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\Sujit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\Sujit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\Sujit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 409, in check
messages.extend(check_resolver(pattern))
File "C:\Users\Sujit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\Sujit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 408, in check
for pattern in self.url_patterns:
File "C:\Users\Sujit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Sujit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'hello.urls' from 'C:\\Users\\Sujit\\Documents\\CS50\\lecture3\\hello\\urls.py'>' 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.
I believe the error message is pretty clear:
The included URLconf <module 'hello.urls' from 'C:\Users\Sujit\Documents\CS50\lecture3\hello\urls.py'> 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.
Make sure this file contains a variable named urlpatterns, and that you can succesfully import it.

update_all_contenttypes seemingly not working with Django 1.8

I was getting the following error upon running a certain function:
django.contrib.contenttypes.models.DoesNotExist: ContentType matching query does not exist.
Based upon ContentType matching query does not exist on post_syncdb I tried doing
from django.contrib.contenttypes.management import update_all_contenttypes
update_all_contenttypes() # make sure all content types exist
at the beginning of that function.
Of course, as ImportError: cannot import name update_all_contenttypes mentions, update_all_contenttypes appears to have been silently removed in Django 1.8 , so that didn't work. Next I tried removing the above snippet and instead adding the following to the beginning of that function:
from django.apps import apps
from django.contrib.contenttypes.management import update_contenttypes
def update_all_contenttypes(**kwargs):
for app_config in apps.get_app_configs():
update_contenttypes(app_config, **kwargs)
update_all_contenttypes()
(Other than the last line, i.e. update_all_contenttypes(), the snippet directly above this comes from https://stackoverflow.com/a/29550255/805141 ).
However, I'm still getting django.contrib.contenttypes.models.DoesNotExist: ContentType matching query does not exist.
The line I'm getting that error on is SomeObject.objects.all().delete()
Here's the full stack trace:
some_function()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/path/to/app/models.py", line XXXX, in some_function
SomeObject.objects.all().delete()
File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 536, in delete
collector.collect(del_query)
File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/deletion.py", line 197, in collect
reverse_dependency=reverse_dependency)
File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/deletion.py", line 97, in add
if not objs:
File /path/to/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 166, in __bool__
self._fetch_all()
File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 965, in _fetch_all
self._result_cache = list(self.iterator())
File "/path/to/virtualenv/lib/python3.4/site-packages/polymorphic/query.py", line 296, in iterator
real_results = self._get_real_instances(base_result_objects)
File "/path/to/virtualenv/lib/python3.4/site-packages/polymorphic/query.py", line 199, in _get_real_instances
real_concrete_class = base_object.get_real_instance_class()
File "/path/to/virtualenv/lib/python3.4/site-packages/polymorphic/polymorphic_model.py", line 105, in get_real_instance_class
model = ContentType.objects.get_for_id(self.polymorphic_ctype_id).model_class()
File "/path/to/virtualenv/lib/python3.4/site-packages/django/contrib/contenttypes/models.py", line 136, in get_for_id
ct = self.get(pk=id)
File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 334, in get
self.model._meta.object_name
django.contrib.contenttypes.models.DoesNotExist: ContentType matching query does not exist.

Django won't serve pages - AttributeError: 'NoneType' object has no attribute 'tags'

I am setting up my site on a production server and have hit a brick wall.
The error below appears running django with gunicorn or just via "manage.py runserver"
Gunicorn/runserver starts fine but when a page is requested this error is reported.
Any advice on where to look or possible causes would be gratefully appreciated.
File "/home/geoff/virtualenvs/mysite/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 125, in handle_request
respiter = self.wsgi(environ, resp.start_response)
File "/home/geoff/virtualenvs/mysite/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__
return self.application(environ, start_response)
File "/home/geoff/virtualenvs/mysite/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_response(request)
File "/home/geoff/virtualenvs/mysite/lib/python2.7/site-packages/django/core/handlers/base.py", line 179, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/home/geoff/virtualenvs/mysite/lib/python2.7/site-packages/django/core/handlers/base.py", line 221, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/home/geoff/virtualenvs/mysite/lib/python2.7/site-packages/django/views/debug.py", line 66, in technical_500_response
html = reporter.get_traceback_html()
File "/home/geoff/virtualenvs/mysite/lib/python2.7/site-packages/django/views/debug.py", line 285, in get_traceback_html
t = Template(TECHNICAL_500_TEMPLATE, name='Technical 500 template')
File "/home/geoff/virtualenvs/mysite/lib/python2.7/site-packages/django/template/base.py", line 125, in __init__
self.nodelist = compile_string(template_string, origin)
File "/home/geoff/virtualenvs/mysite/lib/python2.7/site-packages/django/template/base.py", line 152, in compile_string
parser = parser_class(lexer.tokenize())
File "/home/geoff/virtualenvs/mysite/lib/python2.7/site-packages/django/template/debug.py", line 35, in __init__
super(DebugParser, self).__init__(lexer)
File "/home/geoff/virtualenvs/mysite/lib/python2.7/site-packages/django/template/base.py", line 232, in __init__
self.add_library(lib)
File "/home/geoff/virtualenvs/mysite/lib/python2.7/site-packages/django/template/base.py", line 339, in add_library
self.tags.update(lib.tags)
AttributeError: 'NoneType' object has no attribute 'tags'
If you are updating to django 1.5, removing:
django.contrib.admin.templatetags.adminmedia
From:
TEMPLATE_TAG_MODULES in settings.py
This will dismiss the error.

Django OperationalError: could not fork new process for connection

I've started getting this error on the production environment this morning, after getting Django-storages, Boto, and Django-compressor working to put static files on S3 yesterday, though I don't know if that is related...
OperationalError: could not fork new process for connection: Cannot allocate memory
could not fork new process for connection: Cannot allocate memory
could not fork new process for connection: Cannot allocate memory
Stacktrace (most recent call last):
File "django/core/handlers/base.py", line 89, in get_response
response = middleware_method(request)
File "reversion/middleware.py", line 17, in process_request
if hasattr(request, "user") and request.user.is_authenticated():
File "django/utils/functional.py", line 184, in inner
self._setup()
File "django/utils/functional.py", line 248, in _setup
self._wrapped = self._setupfunc()
File "django/contrib/auth/middleware.py", line 16, in <lambda>
request.user = SimpleLazyObject(lambda: get_user(request))
File "django/contrib/auth/middleware.py", line 8, in get_user
request._cached_user = auth.get_user(request)
File "django/contrib/auth/__init__.py", line 98, in get_user
user_id = request.session[SESSION_KEY]
File "django/contrib/sessions/backends/base.py", line 39, in __getitem__
return self._session[key]
File "django/contrib/sessions/backends/base.py", line 165, in _get_session
self._session_cache = self.load()
File "django/contrib/sessions/backends/db.py", line 19, in load
expire_date__gt=timezone.now()
File "django/db/models/manager.py", line 131, in get
return self.get_query_set().get(*args, **kwargs)
File "django/db/models/query.py", line 361, in get
num = len(clone)
File "django/db/models/query.py", line 85, in __len__
self._result_cache = list(self.iterator())
File "django/db/models/query.py", line 291, in iterator
for row in compiler.results_iter():
File "django/db/models/sql/compiler.py", line 763, in results_iter
for rows in self.execute_sql(MULTI):
File "django/db/models/sql/compiler.py", line 817, in execute_sql
cursor = self.connection.cursor()
File "django/db/backends/__init__.py", line 308, in cursor
cursor = util.CursorWrapper(self._cursor(), self)
File "django/db/backends/postgresql_psycopg2/base.py", line 177, in _cursor
self.connection = Database.connect(**conn_params)
File "psycopg2/__init__.py", line 178, in connect
return _connect(dsn, connection_factory=connection_factory, async=async)
I am deploying the site on Heroku. It works for a bit after I restart the application, but stops working again after a few minutes.
Any ideas as to what might be causing this?
I encountered the same problem trying to set up a simple django web application with a postgresql database on heroku and managed to solve it.
I don't fully understand the error but the fix is fairly simple: when you are passing python lists created by queries to your database, you need to limit the size of the list.
So for example if you are passing as context the following list:
set_list = userSetTable.objects.all()
return render(request, 'fc/user.html', {'set_list': set_list,})
That will cause an error because set_list might be really big. You need to specify a maximum size:
set_list = userSetTable.objects.all()[0:20]
So in a real-world application, you might want to display the list as page results or whatever... you get the point.