Permalink
Browse files

Merge pull request #2 from pigletto/master

Some fixes and cleanups by pigletto
  • Loading branch information...
2 parents c574461 + 9ecb33d commit 3cd3ed37f3d90be0f57284bf35285e57f71a01e6 @hpoul committed Aug 8, 2012
@@ -6,7 +6,7 @@ class PermissionDenied(Exception):
# We can't import it as 'forms' because we've got a package called 'forms' .. how smart.
from django import forms as djangoforms
from django.conf import settings
-from sphene.community.forms import EditProfileForm, Separator
+from sphene.community.forms import EditProfileForm
from sphene.community.signals import profile_edit_init_form, profile_edit_save_form, profile_display
from sphene.community.sphutils import get_sph_setting
from sphene.community.models import CommunityUserProfile
@@ -1,15 +1,20 @@
from django import forms
from django.utils.translation import ugettext_lazy as _, ugettext
+from django.contrib.auth.models import User
+from django.db.models import get_apps, get_models
+from django.contrib.contenttypes.models import ContentType
from sphene.community.signals import profile_edit_init_form
+
class Separator(forms.Field):
def __init__(self, *args, **kwargs):
super(Separator, self).__init__( required = False, *args, **kwargs)
def is_separator(self):
return True
+
class EditProfileForm(forms.Form):
first_name = forms.CharField(label=_(u'First name'), required=False)
last_name = forms.CharField(label=_(u'Last name'), required=False)
@@ -47,10 +52,6 @@ def clean_repassword(self):
return self.cleaned_data
-from django.contrib.auth.models import User
-from django.db.models import signals, get_apps, get_models
-from django.contrib.contenttypes.models import ContentType
-
def get_object_type_choices():
ret = list()
ret.append( ('', _(u'-- Select Object Type --')) )
@@ -72,6 +73,7 @@ def get_object_id_choices(object_type, group):
ret.append( (obj.id, unicode(obj)) )
return ret
+
def get_permission_flag_choices():
ret = list()
@@ -90,6 +92,7 @@ def get_permission_flag_choices():
return ret
+
class EditRoleForm(forms.Form):
name = forms.CharField(label=_(u'Name'))
permission_flags = forms.MultipleChoiceField(label=_(u'Permission flags'))
@@ -101,6 +104,7 @@ def __init__(self, *args, **kwargs):
autosubmit_args = { 'onchange': 'this.form.auto_submit.value = "on";this.form.submit();' }
+
class BasicRoleMemberForm(forms.Form):
# username = forms.CharField()
has_limitations = forms.BooleanField( label=_(u'Has limitations'), widget = forms.CheckboxInput( attrs = autosubmit_args ), required = False, help_text = _(u'Allows you to limit the given permission to only one specific object.') )
@@ -121,6 +125,7 @@ def clean_object_type(self):
except ContentType.DoesNotExist:
raise forms.ValidationError(_(u'Invalid Object Type'))
+
class UsernameRoleMemberForm(forms.Form):
username = forms.CharField(label=_(u'Username'))
@@ -146,12 +151,14 @@ def __init__(self, group, *args, **kwargs):
from sphene.community.models import RoleGroup
self.fields['rolegroup'].queryset = RoleGroup.objects.filter( group = group )
+
class EditRoleMemberForm(UsernameRoleMemberForm, BasicRoleMemberForm):
pass
class EditRoleGroupMemberForm(RoleGroupMemberForm, BasicRoleMemberForm):
pass
+
class UsersSearchForm(forms.Form):
username = forms.CharField(label=_(u'Username'), required=False)
@@ -1,23 +1,26 @@
+import re
+from operator import add
+from time import time
+import logging
+
from django.conf import settings
from django.conf.urls.defaults import *
-from django.core import urlresolvers
from django.http import Http404
from django.shortcuts import get_object_or_404
-
from django.contrib.sites.models import SiteManager, Site
+from django.db import connection
+from django.template.context import RequestContext
+from django.template import loader
+from django.http import HttpResponseForbidden
-
+from sphene.community import PermissionDenied
from sphene.community.models import Group
from sphene.community.sphsettings import get_sph_setting
-
-import re
-import logging
-
-
logger = logging.getLogger('sphene.community.middleware')
+
def my_get_current(self):
try:
group = get_current_group()
@@ -31,7 +34,6 @@ def my_get_current(self):
SiteManager.get_current = my_get_current
-
# If all are used the following order has to remain:
# 1.) ThreadLocals (required)
# 2.) MultiHostMiddleware (optional, but very much recommended!)
@@ -137,10 +139,7 @@ def process_view(self, request, view_func, view_args, view_kwargs):
# copied from http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser
# threadlocals middleware
-try:
- from threading import local
-except ImportError:
- from django.utils._threading_local import local
+from threading import local
#print "Executing module body."
_thread_locals = local()
@@ -198,14 +197,6 @@ def process_request(self, request):
## copied from http://code.djangoproject.com/wiki/PageStatsMiddleware
-import re
-from operator import add
-from time import time
-from django.db import connection
-import logging
-
-logger = logging.getLogger('sphene.community.middleware')
-
class StatsMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
@@ -274,10 +265,10 @@ def process_view(self, request, view_func, view_args, view_kwargs):
return response
-from django.core.handlers.modpython import ModPythonRequest
class ModPythonSetLoggedinUser(object):
def process_request(self, request):
+ from django.core.handlers.modpython import ModPythonRequest
if not isinstance(request, ModPythonRequest):
return None
@@ -300,11 +291,7 @@ def process_request(self, request):
psyco.profile()
return None
-from sphene.community import PermissionDenied
-from django.template.context import RequestContext
-from django.shortcuts import render_to_response
-from django.template import loader
-from django.http import HttpResponseForbidden
+
class PermissionDeniedMiddleware(object):
def process_exception(self, request, exception):
if isinstance(exception, PermissionDenied):
@@ -315,7 +302,6 @@ def process_exception(self, request, exception):
return None
-
class LastModified(object):
""" Middleware that sets the Last-Modified and associated headers,
if requested by the view. (By setting the sph_lastmodified attribute
@@ -1,36 +1,56 @@
+from collections import deque
+from itertools import count
from django import template
register = template.Library()
-def define_page_range(page, pages):
- window = 6
- page_range = range( 1, pages+1 )
- pg = page
- out = []
+def define_page_range(current_page, total_pages, window=6):
+ """ Returns range of pages that contains current page and few pages before and after it.
- if page == -1:
- out = set(page_range[:window/2])
- out.update(set(page_range[-window/2:]))
- out = sorted(out)
- out = list(out)
- if len(out) < len(page_range):
- out.insert(window/2, '...')
- else:
- wnd_start = page_range[:pg]
- wnd_end = page_range[pg:]
+ @current_page - starts from 1
+ @tota_pages - total number of pages
+ @window - maximum number of pages shown with current page - should be even
+
+ Examples (cucumber style):
+ Given window = 6
+ When current_page is 8
+ and total_pages = 20
+ Then I should see: 5 6 7 [8] 9 10 11
+
+ Given window = 6
+ When current_page is 8
+ and total_pages = 9
+ Then I should see: 3 4 5 6 7 [8] 9
- end_correction = window/2
- if len(wnd_start) <= window/2:
- end_correction = window/2 + (window/2-len(wnd_start)) + 1
+ Given window = 6
+ When current_page is 1
+ and total_pages = 9
+ Then I should see: [1] 2 3 4 5 6 7
+ """
+ # maximum length of page range is window + 1
+ maxlen = window + 1
+ page_range = deque(maxlen=maxlen)
- start_correction = window/2 + 1
- if len(wnd_end) <= window/2:
- start_correction = window/2 + (window/2-len(wnd_end)) + 1
+ # minimum possible index is either: (current_page - window) or 1
+ window_start = (current_page - window) if (current_page - window) > 0 else 1
+
+ # maximum possible index is current_page + window or total_pages
+ window_end = total_pages if (current_page + window) > total_pages else (current_page + window)
+
+ # if we have enough pages then we should end at preffered end
+ preffered_end = current_page + int(window / 2.0)
+
+ for i in count(window_start):
+ if i > window_end:
+ # if we're on first page then our window will be [1] 2 3 4 5 6 7
+ break
+ elif i > preffered_end and len(page_range) == maxlen:
+ # if we have enough pages already then stop at preffered_end
+ break
+ page_range.append(i)
+ return list(page_range)
- out = wnd_start[-start_correction:]
- out = out + wnd_end[:end_correction]
- return out
@register.inclusion_tag('sphene/community/_pagination.html', takes_context=True)
def sph_pagination(context, pages, page, url = '', getparam = 'page', compress=0):
@@ -39,7 +59,6 @@ def sph_pagination(context, pages, page, url = '', getparam = 'page', compress=0
if page == -1:
has_next = has_prev = False
-
if compress:
page_range = define_page_range(page, pages)
@@ -204,7 +204,7 @@ def render_node_bbcode(self, node):
class ColorTag(BBTag):
def render_node_xhtml(self, node):
if len(node.children) > 0:
- if node.parameter.lower() in _COLORS or \
+ if node.parameter and node.parameter.lower() in _COLORS or \
_COLOR_REGEXP.match(node.parameter) is not None:
return '<span style="color: ' + node.parameter + ';">' + \
node.render_children_xhtml() + '</span>'
@@ -109,7 +109,7 @@ def __iter__(self):
try:
for ct in categorytyperegistry.get_category_type_list():
choices += ((ct.name, "%s (%s)" % (unicode(ct.label), ct.name)),)
- except:
+ except Exception, e:
# This is also called during syncdb before tables are
# created, so for this case catch all exceptions.
# see http://sct.sphene.net/board/thread/898/
@@ -964,15 +964,15 @@ def get_latest_post(self):
def _hasNewPosts(self, session, user):
if not user.is_authenticated(): return False
- latestPost = self.get_latest_post()
+ latest_post = self.get_latest_post()
categoryLastVisit = self.category.get_lastvisit_date(user)
- if categoryLastVisit > latestPost.postdate:
+ if not latest_post or categoryLastVisit > latest_post.postdate:
return False
try:
threadLastVisit = ThreadLastVisit.objects.filter( user = user,
thread__id = self.id, )[0]
- return threadLastVisit.lastvisit < latestPost.postdate
+ return threadLastVisit.lastvisit < latest_post.postdate
except IndexError:
return True
@@ -11,6 +11,7 @@
from django.contrib import messages
from django.forms.models import modelformset_factory
from django.core.cache import cache
+from django.contrib.auth.decorators import login_required
from sphene.community import PermissionDenied
from sphene.community.permissionutils import has_permission_flag
@@ -891,6 +892,7 @@ def toggle_monitor(request, group, monitortype, object_id, monitor_user_id=None)
return HttpResponseRedirect(obj.get_absolute_url())
+@login_required
def catchup(request, group, category_id):
if category_id == '0':
ThreadLastVisit.objects.filter(user = request.user).delete()

0 comments on commit 3cd3ed3

Please sign in to comment.