Django throws 500 when debug is False in Production

Viewed 141

I am unable to understand why Django 3 fails when I run with DEBUG=False. Also there seems to be a problem with urls:

www.domain.com/ -> Does not work
www.domain.com/en/ -> No problem

The logs seem to mention a million problems but I don't understand what the initial problem is, so I am looking for help:

Exception while resolving variable 'self' in template '404.html'.
Traceback (most recent call last):
  File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 167, in _get_response
    callback, callback_args, callback_kwargs = self.resolve_request(request)
  File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 290, in resolve_request
    resolver_match = resolver.resolve(request.path_info)
  File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 585, in resolve
    raise Resolver404({'tried': tried, 'path': new_path})
django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <URLPattern list> (admin:admin) '^django-admin/'>], [<URLResolver <module 'wagtail.admin.urls' from '/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/wagtail/admin/urls/__init__.py'> (None:None) '^admin/'>], [<URLResolver <module 'wagtail.documents.urls' from '/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/wagtail/documents/urls.py'> (None:None) '^documents/'>], [<URLPattern '^i18n/$' [name='set_language']>], [<URLPattern '^sitemap\.xml$'>], [<URLResolver <URLResolver list> (None:None) 'bg/'>]], 'path': ''}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
  File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/context.py", line 83, in __getitem__
    raise KeyError(key)
KeyError: 'self'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 835, in _resolve_lookup
    if isinstance(current, BaseContext) and getattr(type(current), bit):
AttributeError: type object 'RequestContext' has no attribute 'self'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'self'

#####################
# ...
# Rest of debug lines: https://pastebin.com/5AqDZu11
# ...
#####################

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 837, in _resolve_lookup
    current = getattr(current, bit)
AttributeError: 'NoneType' object has no attribute 'url_name'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'url_name'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [url_name] in None
Internal Server Error: /favicon.ico
"GET /favicon.ico HTTP/1.1" 500 680

I see that it says Internal Server Error: /favicon.ico at the bottom, and I am suspecting this to be the culprit, but the problem persists even if I try a workaround such as:

    url(r'^favicon.ico$', RedirectView.as_view(url=staticfiles_storage.url('img/favicon.ico'), permanent=True)),

I still get 500 ending in:

Internal Server Error: /
"GET / HTTP/1.1" 500 680
"GET /favicon.ico HTTP/1.1" 301 0
"GET /static/img/favicon.be884a05bb00.ico HTTP/1.1" 200 9896

By looking at the very first line, it seems to be an issue with the 404.html

{% extends "base.html" %}

{% block body_class %}template-404{% endblock %}

{% block content %}
    <h1>Page not found</h1>

    <h2>Sorry, this page could not be found.</h2>
{% endblock %}

If I remove the line for extending base.html, it all runs, But I am not clear why.

{% load static wagtailuserbar %}

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
    <head>
        <script type="text/javascript" src="{% static 'js/is-mobile.min.js' %}"></script>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <title>
            {% block title %}
                {% if self.seo_title %}
                    {{ self.seo_title }}
                {% elif self.translated_title %}
                    {{ self.translated_title }}
                {% else %}
                    {{ self.title }}
                {% endif %}
            {% endblock %}
            {% block title_suffix %}
                {% with self.get_site.site_name as site_name %}
                    {% if site_name %}- {{ site_name }}{% endif %}
                {% endwith %}
            {% endblock %}
        </title>
        <link rel="shortcut icon" href="{% static 'img/favicon.ico' %}">
        <meta name="viewport" content="width=device-width, initial-scale=1" />

        <meta name="description" content="{% block meta_description %}{% endblock %}" />
        <meta name="keywords" content="{% block meta_keywords %}{% endblock %}" />

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" type="text/css" href="{% static 'slick/slick.css' %}"/>

        {# Global stylesheets #}
        {% if debug %}
        <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}">
        {% else %}
        <link rel="stylesheet" type="text/css" href="{% static 'css/main.min.css' %}">
        {% endif %}

        {% if not request.is_preview %}
            {# The page is not in preview mode #}
            {# Put google analytics, mixpanel, etc... here #}
        {% endif %}

        {% block extra_css %}
            {# Override this in templates to add extra stylesheets #}
        {% endblock %}
    </head>

    <body class="{% block body_class %}{% endblock %}">
        {% wagtailuserbar %}
        {% block navigation %}
        {% include 'partials/_navigation.html' %}
        {% endblock %}

        <div class="content">{% block content %}{% endblock %}</div>

        {% block footer %}
        {% include 'partials/_footer.html' %}
        {% endblock %}

        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <script type="text/javascript" src="{% static 'slick/slick.min.js' %}"></script>
        <script src="https://unpkg.com/scrollreveal@3.3.5/dist/scrollreveal.min.js"></script>
        <script type="text/javascript" src="{% static 'js/parallax.min.js' %}"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/parallax/3.1.0/parallax.min.js"></script>

        <script id="developedby" data-client-id="d640d636-cbe0-493c-b51a-124becd2cd6d" src="https://hakomo.s3.eu-central-1.amazonaws.com/static/js/webdevelopmentbyhakomo.js"></script>
        <script src="{% static 'js/min/main.js' %}"></script>
        {% block extra_js %}
            {# Override this in templates to add extra javascript #}
        {% endblock %}
    </body>
</html>

My urls.py:


urlpatterns = [
    url(r'^django-admin/', admin.site.urls),

    url(r'^admin/', include(wagtailadmin_urls)),
    url(r'^documents/', include(wagtaildocs_urls)),

    url(r'^i18n/$', set_language, name='set_language'),
    url(r'^sitemap\.xml$', sitemap, sitemaps),
    url(r'^favicon.ico$', RedirectView.as_view(url=staticfiles_storage.url('img/favicon.ico'), permanent=True)),
]

urlpatterns += i18n_patterns(
    # These URLs will have /<language_code>/ appended to the beginning

    url(r'', include(content_urls)),

    url(r'^search/$', search_views.search, name='search'),

 
    url(r'', include(wagtail_urls)),

)


if settings.DEBUG:
    from django.conf.urls.static import static
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns

    # Serve static and media files from development server
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


  1. So besides understanding why extending base is an issue,

  2. I am also wondering why at all we are getting 404 to begin with.

Thanks for any help

1 Answers

The First Line Says :

Exception while resolving variable 'self' in template '404.html'.

And You have used self in your base.html, therefore when you remove

{% extends "base.html" %}

It all works.

So Django is unable to resolve the variable self,

Please update your Question with views.py which passes this context variable self to base.html

That will clear out things for sure

Also we should avoid using reserved keywords like self as variable name in Python

Related