django-admin-tools-stats icon indicating copy to clipboard operation
django-admin-tools-stats copied to clipboard

Issue at admin's page

Open MiroslawCzechorowski opened this issue 8 years ago • 1 comments

ImportError at /admin/ cannot import name 'smart_unicode' Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 1.10.4 Exception Type: ImportError Exception Value: cannot import name 'smart_unicode' Exception Location: /myvenv/lib/python3.5/site-packages/cache_utils/utils.py in , line 2 Python Executable: /myvenv/bin/python Python Version: 3.5.2 Python Path: ['/Users/Miro/Desktop/DjangoProjektApp', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload', '/Users/Miro/Desktop/DjangoProjektApp/myvenv/lib/python3.5/site-packages'] Server time: Mon, 2 Jan 2017 23:26:32 +0000 Error during template rendering

In template /myvenv/lib/python3.5/site-packages/admin_tools/dashboard/templates/admin/index.html, error at line 5 cannot import name 'smart_unicode' 1 {% extends "admin:admin/index.html" %} 2 {% load admin_tools_dashboard_tags %} 3 {% block extrastyle %} 4 {{ block.super }} 5 {% block dashboard_css %}{% admin_tools_render_dashboard_css %}{% endblock %} 6 {% endblock %} 7 {% block coltype %}{% endblock %} 8 {% block bodyclass %}dashboard{% endblock %} 9 {% block content_title %}{% endblock %} 10 {% block content %} 11 {% admin_tools_render_dashboard %} 12 {% endblock %} 13 {% block sidebar %}{% endblock %}

When I changed smart_unicode to smart_text I get following error:

File "/myvenv/lib/python3.5/site-packages/cache_utils/utils.py", line 29, in _func_type argnames = func.func_code.co_varnames[:func.func_code.co_argcount] AttributeError: 'function' object has no attribute 'func_code'

Can anyone help me to fix this ?

MiroslawCzechorowski avatar Jan 02 '17 23:01 MiroslawCzechorowski

According to this link https://groups.google.com/forum/#!topic/django-blog-zinnia/-AU2EzCL9M0 you can edit your local repo and change smart_unicode for smart_text If that fix your issue you may create a new branch applying that change and submitting your PR.

I traced back the origin of the error and I found that it is raised in this function:

# admin_tools/dashboard/utils.py
from importlib import import_module

def _get_dashboard_cls(dashboard_cls, context):
    if isinstance(dashboard_cls, dict):
        curr_url = context.get('request').path
        for key in dashboard_cls:
            admin_site_mod, admin_site_inst = key.rsplit('.', 1)
            admin_site_mod = import_module(admin_site_mod)
            admin_site = getattr(admin_site_mod, admin_site_inst)
            admin_url = reverse('%s:index' % admin_site.name)
            if curr_url.startswith(admin_url):
                mod, inst = dashboard_cls[key].rsplit('.', 1)
                mod = import_module(mod) # The error is raised on this line.
                return getattr(mod, inst)

More insights:

ipdb> import_module
<function import_module at 0x10fceba60>
ipdb> mod
'dashboard'
ipdb> dashboard_cls
'dashboard.CustomIndexDashboard'
ipdb> import_module(mod)
*** ImportError: cannot import name 'smart_unicode'
ipdb> 

And finally this is my class for CustomIndexDashboard:

from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse

from admin_tools.dashboard import modules, Dashboard, AppIndexDashboard
from admin_tools.utils import get_admin_site_name
from admin_tools_stats.modules import DashboardCharts, get_active_graph


class CustomIndexDashboard(Dashboard):
    """
    Custom index dashboard for Loany.
    """
    def init_with_context(self, context):
        site_name = get_admin_site_name(context)
        # append a link list module for "quick links"
        self.children.append(modules.LinkList(
            _('Quick links'),
            layout='inline',
            draggable=False,
            deletable=False,
            collapsible=False,
            children=[
                [_('Return to site'), '/'],
                [_('Change password'),
                 reverse('%s:password_change' % site_name)],
                [_('Log out'), reverse('%s:logout' % site_name)],
            ]
        ))

        # append an app list module for "Applications"
        self.children.append(modules.AppList(
            _('Applications'),
            exclude=('django.contrib.*',),
        ))

        # append an app list module for "Administration"
        self.children.append(modules.AppList(
            _('Administration'),
            models=('django.contrib.*',),
        ))

        # append a recent actions module
        self.children.append(modules.RecentActions(_('Recent Actions'), 5))

        # append a feed module
        self.children.append(modules.Feed(
            _('Latest Django News'),
            feed_url='http://www.djangoproject.com/rss/weblog/',
            limit=5
        ))

        # append an app list module
        self.children.append(modules.AppList(
            _('Dashboard Stats Settings'),
            models=('admin_tools_stats.*', ),
        ))

        # Copy following code into your custom dashboard
        # append following code after recent actions module or
        # a link list module for "quick links"
        graph_list = get_active_graph()
        for i in graph_list:
            kwargs = {}
            kwargs['require_chart_jscss'] = True
            kwargs['graph_key'] = i.graph_key

            for key in context['request'].POST:
                if key.startswith('select_box_'):
                    kwargs[key] = context['request'].POST[key]

            self.children.append(DashboardCharts(**kwargs))

        # append another link list module for "support".
        self.children.append(modules.LinkList(
            _('Support'),
            children=[
                {
                    'title': _('Django documentation'),
                    'url': 'http://docs.djangoproject.com/',
                    'external': True,
                },
                {
                    'title': _('Django "django-users" mailing list'),
                    'url': 'http://groups.google.com/group/django-users',
                    'external': True,
                },
                {
                    'title': _('Django irc channel'),
                    'url': 'irc://irc.freenode.net/django',
                    'external': True,
                },
            ]
        ))

Then l found that the smart_unicode error is being raised on this imports.

ipdb> from admin_tools_stats.modules import DashboardCharts
*** ImportError: cannot import name 'smart_unicode'
ipdb> from admin_tools_stats.modules import get_active_graph
*** ImportError: cannot import name 'smart_unicode'
ipdb> 

Digging deeper the error seems to be in this import:

In [5]: from cache_utils.decorators import cached
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-5-6d0aa8bcb569> in <module>()
----> 1 from cache_utils.decorators import cached

/Users/user/code/project/lib/python3.6/site-packages/cache_utils/decorators.py in <module>()
      2 from django.core.cache import cache
      3 from django.utils.functional import wraps
----> 4 from cache_utils.utils import _cache_key, _func_info, _func_type, sanitize_memcached_key
      5 
      6 def cached(timeout, group=None):

/Users/user/code/project/lib/python3.6/site-packages/cache_utils/utils.py in <module>()
      1 from hashlib import md5
----> 2 from django.utils.encoding  import smart_unicode
      3 
      4 CONTROL_CHARACTERS = set([chr(i) for i in range(0,33)])
      5 CONTROL_CHARACTERS.add(chr(127))

ImportError: cannot import name 'smart_unicode'

Finally the error:

# project/lib/python3.6/site-packages/cache_utils/utils.py
from hashlib import md5
from django.utils.encoding  import smart_unicode

So we need to add support for python 3 for this package: https://bitbucket.org/kmike/django-cache-utils/ please read: https://bitbucket.org/kmike/django-cache-utils/issues/12/add-compatibility-with-python-3

And after that update requirements.txtto point the patched version of django-cache-utils

klahnen avatar Jan 25 '17 22:01 klahnen