Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't call reload(sys), fixes Python3. #394

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions demo_app/app/adminx.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import xadmin
from xadmin import views
from models import IDC, Host, MaintainLog, HostGroup, AccessRecord
from .models import IDC, Host, MaintainLog, HostGroup, AccessRecord
from xadmin.layout import Main, TabHolder, Tab, Fieldset, Row, Col, AppendedText, Side
from xadmin.plugins.inline import Inline
from xadmin.plugins.batch import BatchChangeAction
Expand Down Expand Up @@ -76,7 +76,7 @@ def open_web(self, instance):
search_fields = ['name', 'ip', 'description']
list_filter = ['idc', 'guarantee_date', 'status', 'brand', 'model',
'cpu', 'core_num', 'hard_disk', 'memory', ('service_type',xadmin.filters.MultiSelectFieldListFilter)]

list_quick_filter = ['service_type',{'field':'idc__name','limit':10}]
list_bookmarks = [{'title': "Need Guarantee", 'query': {'status__exact': 2}, 'order': ('-guarantee_date',), 'cols': ('brand', 'guarantee_date', 'service_type')}]

Expand Down Expand Up @@ -118,16 +118,16 @@ def open_web(self, instance):
)
inlines = [MaintainInline]
reversion_enable = True

data_charts = {
"host_service_type_counts": {'title': u"Host service type count", "x-field": "service_type", "y-field": ("service_type",),
"host_service_type_counts": {'title': u"Host service type count", "x-field": "service_type", "y-field": ("service_type",),
"option": {
"series": {"bars": {"align": "center", "barWidth": 0.8,'show':True}},
"series": {"bars": {"align": "center", "barWidth": 0.8,'show':True}},
"xaxis": {"aggregate": "count", "mode": "categories"},
},
},
}

class HostGroupAdmin(object):
list_display = ('name', 'description')
list_display_links = ('name',)
Expand Down Expand Up @@ -183,17 +183,17 @@ def avg_count(self, instance):
data_charts = {
"user_count": {'title': u"User Report", "x-field": "date", "y-field": ("user_count", "view_count"), "order": ('date',)},
"avg_count": {'title': u"Avg Report", "x-field": "date", "y-field": ('avg_count',), "order": ('date',)},
"per_month": {'title': u"Monthly Users", "x-field": "_chart_month", "y-field": ("user_count", ),
"per_month": {'title': u"Monthly Users", "x-field": "_chart_month", "y-field": ("user_count", ),
"option": {
"series": {"bars": {"align": "center", "barWidth": 0.8,'show':True}},
"series": {"bars": {"align": "center", "barWidth": 0.8,'show':True}},
"xaxis": {"aggregate": "sum", "mode": "categories"},
},
},
}

def _chart_month(self,obj):
return obj.date.strftime("%B")


xadmin.sites.site.register(Host, HostAdmin)
xadmin.sites.site.register(HostGroup, HostGroupAdmin)
Expand Down
5 changes: 1 addition & 4 deletions demo_app/demo/settings.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
# Django settings for wictrl project.

import sys
import os.path

reload(sys)
sys.setdefaultencoding('utf-8')

gettext = lambda s: s

PROJECT_ROOT = os.path.join(
Expand Down
9 changes: 2 additions & 7 deletions tests/xtests/site/apps.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
#!/usr/bin/env python
#coding:utf-8
import sys
if sys.getdefaultencoding()=='ascii':
reload(sys)
sys.setdefaultencoding('utf-8')

# -*- coding: utf-8 -*-
from django.apps import AppConfig


class SiteApp(AppConfig):
name = "site"
9 changes: 2 additions & 7 deletions tests/xtests/view_base/apps.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
#!/usr/bin/env python
#coding:utf-8
import sys
if sys.getdefaultencoding()=='ascii':
reload(sys)
sys.setdefaultencoding('utf-8')

# -*- coding: utf-8 -*-
from django.apps import AppConfig


class ViewBaseApp(AppConfig):
name = "view_base"
4 changes: 2 additions & 2 deletions xadmin/adminx.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import xadmin
from models import UserSettings, Log
from .models import UserSettings, Log
from xadmin.layout import *

from django.utils.translation import ugettext_lazy as _, ugettext
Expand All @@ -14,7 +14,7 @@ class LogAdmin(object):

def link(self, instance):
if instance.content_type and instance.object_id and instance.action_flag != 'delete':
admin_url = self.get_admin_url('%s_%s_change' % (instance.content_type.app_label, instance.content_type.model),
admin_url = self.get_admin_url('%s_%s_change' % (instance.content_type.app_label, instance.content_type.model),
instance.object_id)
return "<a href='%s'>%s</a>" % (admin_url, _('Admin Object'))
else:
Expand Down
42 changes: 20 additions & 22 deletions xadmin/filters.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django.db import models
from django.core.exceptions import ImproperlyConfigured
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.template.loader import get_template
Expand All @@ -17,7 +16,7 @@
FILTER_PREFIX = '_p_'
SEARCH_VAR = '_q_'

from util import (get_model_from_relation,
from .util import (get_model_from_relation,
reverse_field_path, get_limit_choices_to_from_path, prepare_lookup_value)


Expand Down Expand Up @@ -192,7 +191,7 @@ def choices(self):
}
for lookup, title in self.field.flatchoices:
yield {
'selected': smart_unicode(lookup) == self.lookup_exact_val,
'selected': lookup == self.lookup_exact_val,
'query_string': self.query_string({self.lookup_exact_name: lookup}),
'display': title,
}
Expand Down Expand Up @@ -408,7 +407,7 @@ def choices(self):
}
for pk_val, val in self.lookup_choices:
yield {
'selected': self.lookup_exact_val == smart_unicode(pk_val),
'selected': self.lookup_exact_val == pk_val,
'query_string': self.query_string({
self.lookup_exact_name: pk_val,
}, [self.lookup_isnull_name]),
Expand All @@ -428,62 +427,62 @@ def choices(self):
@manager.register
class MultiSelectFieldListFilter(ListFieldFilter):
""" Delegates the filter to the default filter and ors the results of each

Lists the distinct values of each field as a checkbox
Uses the default spec for each
Uses the default spec for each

"""
template = 'xadmin/filters/checklist.html'
lookup_formats = {'in': '%s__in'}
cache_config = {'enabled':False,'key':'quickfilter_%s','timeout':3600,'cache':'default'}

@classmethod
def test(cls, field, request, params, model, admin_view, field_path):
return True

def get_cached_choices(self):
if not self.cache_config['enabled']:
return None
c = caches(self.cache_config['cache'])
return c.get(self.cache_config['key']%self.field_path)

def set_cached_choices(self,choices):
if not self.cache_config['enabled']:
return
c = caches(self.cache_config['cache'])
return c.set(self.cache_config['key']%self.field_path,choices)

def __init__(self, field, request, params, model, model_admin, field_path,field_order_by=None,field_limit=None,sort_key=None,cache_config=None):
super(MultiSelectFieldListFilter,self).__init__(field, request, params, model, model_admin, field_path)

# Check for it in the cachce
if cache_config is not None and type(cache_config)==dict:
self.cache_config.update(cache_config)

if self.cache_config['enabled']:
self.field_path = field_path
choices = self.get_cached_choices()
if choices:
self.lookup_choices = choices
return

# Else rebuild it
queryset = self.admin_view.queryset().exclude(**{"%s__isnull"%field_path:True}).values_list(field_path, flat=True).distinct()
queryset = self.admin_view.queryset().exclude(**{"%s__isnull"%field_path:True}).values_list(field_path, flat=True).distinct()
#queryset = self.admin_view.queryset().distinct(field_path).exclude(**{"%s__isnull"%field_path:True})

if field_order_by is not None:
# Do a subquery to order the distinct set
queryset = self.admin_view.queryset().filter(id__in=queryset).order_by(field_order_by)

if field_limit is not None and type(field_limit)==int and queryset.count()>field_limit:
queryset = queryset[:field_limit]

self.lookup_choices = [str(it) for it in queryset.values_list(field_path,flat=True) if str(it).strip()!=""]
if sort_key is not None:
self.lookup_choices = sorted(self.lookup_choices,key=sort_key)

if self.cache_config['enabled']:
self.set_cached_choices(self.lookup_choices)
self.set_cached_choices(self.lookup_choices)

def choices(self):
self.lookup_in_val = (type(self.lookup_in_val) in (tuple,list)) and self.lookup_in_val or list(self.lookup_in_val)
Expand All @@ -494,7 +493,7 @@ def choices(self):
}
for val in self.lookup_choices:
yield {
'selected': smart_unicode(val) in self.lookup_in_val,
'selected': val in self.lookup_in_val,
'query_string': self.query_string({self.lookup_in_name: ",".join([val]+self.lookup_in_val),}),
'remove_query_string': self.query_string({self.lookup_in_name: ",".join([v for v in self.lookup_in_val if v != val]),}),
'display': val,
Expand Down Expand Up @@ -535,7 +534,6 @@ def choices(self):
if val is None:
include_none = True
continue
val = smart_unicode(val)
yield {
'selected': self.lookup_exact_val == val,
'query_string': self.query_string({self.lookup_exact_name: val},
Expand Down
6 changes: 3 additions & 3 deletions xadmin/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from django.core.urlresolvers import NoReverseMatch, reverse
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models.base import ModelBase
from django.utils.encoding import python_2_unicode_compatible, smart_text, smart_unicode

from django.db.models.signals import post_migrate
from django.contrib.auth.models import Permission
Expand All @@ -19,6 +18,7 @@

AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')


def add_view_permissions(sender, **kwargs):
"""
This syncdb hooks takes care of adding a view permission too all our
Expand Down Expand Up @@ -77,7 +77,7 @@ def default(self, o):
try:
return super(JSONEncoder, self).default(o)
except Exception:
return smart_unicode(o)
return unicode(o)


class UserSettings(models.Model):
Expand Down Expand Up @@ -162,7 +162,7 @@ class Meta:
ordering = ('-action_time',)

def __repr__(self):
return smart_text(self.action_time)
return self.action_time

def __str__(self):
if self.action_flag == 'create':
Expand Down
7 changes: 3 additions & 4 deletions xadmin/plugins/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.template.response import TemplateResponse
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _, ungettext
from django.utils.text import capfirst
Expand All @@ -24,7 +23,7 @@


def action_checkbox(obj):
return checkbox.render(ACTION_CHECKBOX_NAME, force_unicode(obj.pk))
return checkbox.render(ACTION_CHECKBOX_NAME, obj.pk)
action_checkbox.short_description = mark_safe(
'<input type="checkbox" id="action-toggle" />')
action_checkbox.allow_tags = True
Expand Down Expand Up @@ -102,9 +101,9 @@ def do_action(self, queryset):
return None

if len(queryset) == 1:
objects_name = force_unicode(self.opts.verbose_name)
objects_name = self.opts.verbose_name
else:
objects_name = force_unicode(self.opts.verbose_name_plural)
objects_name = self.opts.verbose_name_plural

if perms_needed or protected:
title = _("Cannot delete %(name)s") % {"name": objects_name}
Expand Down
7 changes: 3 additions & 4 deletions xadmin/plugins/ajax.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from collections import OrderedDict
from django.forms.utils import ErrorDict
from django.utils.html import escape
from django.utils.encoding import force_unicode
from xadmin.sites import site
from xadmin.views import BaseAdminPlugin, ListAdminView, ModelFormAdminView, DetailAdminView

Expand All @@ -16,9 +15,9 @@ def init_request(self, *args, **kwargs):


class AjaxListPlugin(BaseAjaxPlugin):

def get_list_display(self,list_display):
list_fields = [field for field in self.request.GET.get('_fields',"").split(",")
list_fields = [field for field in self.request.GET.get('_fields',"").split(",")
if field.strip() != ""]
if list_fields:
return list_fields
Expand All @@ -27,7 +26,7 @@ def get_list_display(self,list_display):
def get_result_list(self, response):
av = self.admin_view
base_fields = self.get_list_display(av.base_list_display)
headers = dict([(c.field_name, force_unicode(c.text)) for c in av.result_headers(
headers = dict([(c.field_name, c.text) for c in av.result_headers(
).cells if c.field_name in base_fields])

objects = [dict([(o.field_name, escape(str(o.value))) for i, o in
Expand Down
5 changes: 2 additions & 3 deletions xadmin/plugins/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from django.core.exceptions import PermissionDenied
from django.forms.models import modelform_factory
from django.template.response import TemplateResponse
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _, ugettext_lazy
from xadmin.layout import FormHelper, Layout, Fieldset, Container, Col
Expand Down Expand Up @@ -129,9 +128,9 @@ def do_action(self, queryset):
self.form_obj.helper = helper
count = len(queryset)
if count == 1:
objects_name = force_unicode(self.opts.verbose_name)
objects_name = self.opts.verbose_name
else:
objects_name = force_unicode(self.opts.verbose_name_plural)
objects_name = self.opts.verbose_name_plural

context = self.get_context()
context.update({
Expand Down
9 changes: 4 additions & 5 deletions xadmin/plugins/chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from django.http import HttpResponseNotFound
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
from django.utils.encoding import smart_unicode
from django.db import models
from django.utils.http import urlencode
from django.utils.translation import ugettext_lazy as _, ugettext
Expand All @@ -16,7 +15,7 @@
from xadmin.sites import site
from xadmin.views import BaseAdminPlugin, ListAdminView
from xadmin.views.dashboard import ModelBaseWidget, widget_manager
from xadmin.util import lookup_field, label_for_field, force_unicode, json
from xadmin.util import lookup_field, label_for_field, json


@widget_manager.register
Expand Down Expand Up @@ -77,7 +76,7 @@ def default(self, o):
try:
return super(JSONEncoder, self).default(o)
except Exception:
return smart_unicode(o)
return o


class ChartsPlugin(BaseAdminPlugin):
Expand Down Expand Up @@ -124,8 +123,8 @@ def get(self, request, name):
self.y_fields = (
y_fields,) if type(y_fields) not in (list, tuple) else y_fields

datas = [{"data":[], "label": force_unicode(label_for_field(
i, self.model, model_admin=self))} for i in self.y_fields]
datas = [{"data":[], "label": label_for_field(
i, self.model, model_admin=self)} for i in self.y_fields]

self.make_result_list()

Expand Down
Loading