def get(self, user): import urllib user = urllib.unquote(user) if '@' in user: u = users.User(user) else: u = users.User(user+'@gmail.com') messages= model.Message.all().filter('user ='******'-date').fetch(1000) if not messages and not users.get_current_user(): raise tornado.web.HTTPError(404) if not messages and users.get_current_user().email() != u.email(): raise tornado.web.HTTPError(404) paginator = ObjectPaginator(messages, 10, 1) try: page = int(self.get_argument('page', '1')) except ValueError: page = 1 try: records = paginator.get_page(page-1) except: records = paginator.get_page(0) page = 1 self.render('user.html', **{'u':u, 'messages':records, 'paginator':paginator, "next" : paginator.has_next_page(page-1), 'previous':paginator.has_previous_page(page-1), 'previous_page_number':page-1, 'next_page_number':page+1, "page" : page})
def get(self, slug): s = utils.lookup_agency_alias(slug) if s: return self.redirect('/agency/%s/' % (s)) agency = utils.get_agency(slug) if not agency: raise tornado.web.HTTPError(404) messages =model.MessageAgency.all().filter('agency', agency).order('-date').fetch(1000) paginator = ObjectPaginator(messages, 10, 1) try: page = int(self.get_argument('page', '1')) except ValueError: page = 1 if page <= 0: page = 1 try: records = paginator.get_page(page-1) except: records = paginator.get_page(0) page = 1 self.render('agency.html', agency=agency, messages=records, paginator=paginator, next=paginator.has_next_page(page-1), previous=paginator.has_previous_page(page-1), previous_page_number=page-1, next_page_number=page+1, page=page)
def get_page(self, page_num=None): try: if page_num is None: return ObjectPaginator.get_page(self, self.current_page - 1) else: return ObjectPaginator.get_page(self, page_num) except InvalidPage: return None
def listNamespaces(page=0, page_size=10): namespaces = memcache.get("namespace_list") if not namespaces: query = db.GqlQuery("SELECT * FROM Namespace WHERE owner = :1", users.get_current_user()) namespaces = query.fetch((page_size * 10)) memcache.set("namespace_list", namespaces, (60*1)) paginator = ObjectPaginator(namespaces, page_size) try: items = paginator.get_page(page) except InvalidPage: raise http.Http404 options = { "items": items, "is_paginated": True, "results_per_page" : page_size, "has_next": paginator.has_next_page(page), "has_previous": paginator.has_previous_page(page), "page": page + 1, "next": page + 1, "previous": page - 1, "pages": paginator.pages, } return options
def get(self): user = users.get_current_user() if not user: return self.redirect('/admin/index') page = self.request.get('page') try: page = int(page) - 1 except: page = 0 userid = self.request.get('userid') datas = User.get_by_id(long(userid)) paginator = ObjectPaginator(datas.picture_set, PICTUREPAGE) if page >= paginator.pages: page = paginator.pages - 1 params = { "datas": paginator.get_page(page), "pages": range(1, paginator.pages + 1), "page": page + 1, "userid": datas } fpath = os.path.join(os.path.dirname(__file__), 'template/admin/user', 'showpicture.html') html = template.render(fpath, params) self.response.out.write(html) return
def _get(self): upload_url = blobstore.create_upload_url('/image/submit') page = self.request.get("page") try: page = int(page) - 1 except: page = 0 query = ImageAsset.all().order('-created_at') images = query.fetch(1000) if (self.PAGESIZE * page)/1000 > 0: cursor_iterations = (self.PAGESIZE * page)/1000 for i in range(0, cursor_iterations): logging.info("Iterating though images %d/%d" % (i,cursor_iterations)) cursor = query.cursor() query.with_cursor() images = query.fetch(1000) paginator = ObjectPaginator(images, self.PAGESIZE) #if page>=paginator.pages: # page = paginator.pages - 1 #if page < 0: # page = 0 self.template_values = { "images" : paginator.get_page(page), "pages" : range(page+1,page+paginator.pages+1), "page" : page+1, "upload_url" : upload_url } self.page_display(self,"templates/gallery.html")
def listMessages(page=0, page_size=10): messages = memcache.get("message_list_%s" % (users.get_current_user())) if not messages: query = db.GqlQuery("SELECT * FROM Message WHERE namespace_owner = :1 ORDER BY created DESC", users.get_current_user()) messages = query.fetch((page_size * 10)) memcache.set("message_list_%s" % (users.get_current_user()), messages, (60*1)) paginator = ObjectPaginator(messages, page_size) try: items = paginator.get_page(page) except InvalidPage: raise http.Http404 options = { "items": items, "is_paginated": True, "results_per_page" : page_size, "has_next": paginator.has_next_page(page), "has_previous": paginator.has_previous_page(page), "page": page + 1, "next": page + 1, "previous": page - 1, "pages": paginator.pages, } return options
def get(self,page): user = users.get_current_user() if user: if users.is_current_user_admin(): try: page = int(page) - 1 except: page = 0 uploads = Upload.all() paginator = ObjectPaginator(uploads,10) if page>=paginator.pages: page = paginator.pages - 1 pages = range(1,paginator.pages+1) page_max = len(pages) template_values = { 'images': paginator.get_page(page), 'user': user, 'pages': pages, 'page_max': page_max, 'page': page+1 } path = os.path.join(os.path.dirname(__file__), 'templates/index.html') self.response.out.write(template.render(path, template_values)) else: template_values = {} path = os.path.join(os.path.dirname(__file__), 'templates/404.html') self.response.out.write(template.render(path, template_values)) else: self.redirect(users.create_login_url(self.request.uri))
def get(self): page = int(self.request.get('page', '0')) paginator = ObjectPaginator(db.GqlQuery('SELECT * FROM BlogPostModel ORDER BY created DESC'),10) blogposts = paginator.get_page(page) nextPageNumber = 0 prevPageNumber = 0 if paginator.has_next_page(page): nextPageNumber = str(page+1) if paginator.has_previous_page(page): prevPageNumber = str(page-1) template_values = { 'menulinks':menuLinks(), 'blogposts': blogposts, 'user': authenticatedUser(sessions.Session()), 'nextPageNumber': nextPageNumber, 'prevPageNumber': prevPageNumber, } path = os.path.join(os.path.dirname(__file__), 'news.html') self.response.out.write(template.render(path, template_values))
def get(self): user = self.getAuthentificatedUser() page = self.request.get('page') try: page = int(page) - 1 except: page = 0 allUsers = self.getUsers().order('login') paginator = ObjectPaginator(allUsers, 50) if page >= paginator.pages or page < 0: page = paginator.pages - 1 if page >= paginator.pages - 1: next = None else: next = page + 2 if page < 1: prev = None else: prev = page forum = self.getForumInstance() template_values = { 'url' : users.CreateLogoutURL(self.request.uri), 'user' : user.nickname(), 'forum' : forum, 'users' : paginator.get_page(page), 'pages' : range(1, paginator.pages + 1), 'page' : page+1, 'next' : next, 'prev' : prev, } #for user in self.getUsers().order('-login'): #print user.login path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'viewUsers.htm')) self.response.out.write(template.render(path, template_values))
def list(request, listing_id): user = users.GetCurrentUser() if user is None: return http.HttpResponseForbidden('You must be signed in to view listing values') listing_values = None listing = None lvs_paginator = None if request.GET.has_key('page'): page = int(request.GET['page']) else: page = 0 if listing_id: listing = get_listing(listing_id) lvs = ListingValue.all().order('-date').filter('listing_key = ', str(listing.key())) lvs_paginator = ObjectPaginator(lvs, 10) listing_values = lvs_paginator.get_page(page) if listing is None or listing_values is None or listing_id is None: return http.HttpResponseNotFound( 'No values exists for that listing (%r)' % listing_id) paginator = {} paginator['has_previous_page'] = lvs_paginator.has_previous_page(page) paginator['has_next_page'] = lvs_paginator.has_next_page(page) paginator['next_page_number'] = page+1 paginator['previous_page_number'] = page-1 return common.respond(request, user, 'values_list', {'listing': listing, 'listing_values' : listing_values, 'paginator': paginator})
def get(self): user = users.get_current_user() if not user: return self.redirect('/admin/index') page = self.request.get('page') zoomFlg = self.request.get('zoomFlg') searchLabel = self.request.get('searchLabel') try: page = int(page) - 1 except: page = 0 if searchLabel != "": datas = Picture.gql("WHERE label =:1", searchLabel) else: datas = Picture.all() paginator = ObjectPaginator(datas, PAGE) if page >= paginator.pages: page = paginator.pages - 1 params = { "datas": paginator.get_page(page), "pages": range(1, paginator.pages + 1), "page": page + 1, 'zoomFlg': zoomFlg, 'searchLabel': searchLabel } fpath = os.path.join(os.path.dirname(__file__), 'template/admin/picture', 'list.html') html = template.render(fpath, params) self.response.out.write(html) return
def user_page(request, username): user = get_object_or_404(User, username=username) query_set = user.bookmark_set.order_by('-id') paginator = ObjectPaginator(query_set, ITEM_PER_PAGE) is_friend = Friendship.objects.filter( from_friend=request.user, to_friend=user ) try: page = int(request.GET['page']) except: page = 1 try: bookmarks = paginator.get_page(page - 1) except: raise Http404 variables = RequestContext(request, { 'bookmarks': bookmarks, 'username': username, 'show_tags': True, 'show_edit': username == request.user.username, 'show_paginator': paginator.pages > 1, 'has_prev': paginator.has_previous_page(page - 1), 'has_next': paginator.has_next_page(page - 1), 'page': page, 'pages': paginator.pages, 'next_page': page + 1, 'prev_page': page - 1, 'is_friend': is_friend }) return render_to_response('user_page.html', variables)
def _getPagenator(selection, page): try: current = int(page) except: current = 1 paginator = ObjectPaginator(selection, PAGESIZE) maxpage = paginator.pages + 1 if current >= maxpage: current = maxpage - 1 elif current <= 0: current = 1 if(current > PAGERANGE): start = current - round(PAGERANGE / 2) else: start = 1 end = start + PAGERANGE if end > maxpage: end = maxpage paginator.items = paginator.get_page(current - 1) paginator.range = range(start, end) paginator.current = current paginator.previous = current - 1 paginator.next = current + 1 return paginator
def topics(request): if not request.user.is_authenticated(): return HttpResponseRedirect("/") # retrieve related topics user = request.user topics = Topic.objects.filter(Q(user1=user) | Q(user2=user)).order_by('-update_on') paginator = ObjectPaginator(topics, 10) try: page = int(request.GET.get('page', '1')) topics = paginator.get_page(page - 1) except: page = 1 topics = [] # prepare data to display messages_command = [] TopicDto = type('TopicDto', (object,), {}) for topicItem in topics: topicDto = TopicDto() topicDto.topic = topicItem topicDto.companion = topicItem.get_companion(user) topicDto.not_read_messages_count = topicItem.get_count_of_not_read_messages(user) messages_command.append(topicDto) page_title = user.get_profile().get_name().encode('utf8') + ' : ' + u'Список приватних повідомлень '.encode('utf8') return render_to_response('messages/topics.html', {'pagetitle': page_title, 'u': user.get_profile(), 'can_subscribe': False, 'can_unsubscribe': False, 'page':page, 'paginator':paginator, 'messages_command': messages_command, 'topics': topics}, context_instance=RequestContext(request))
def _run_query(cls, query, pagination=False, current_page=0, items_per_page=10): if pagination: paginator = ObjectPaginator(query, items_per_page) synopsis_list = paginator.get_page(current_page) else: paginator = None synopsis_list = query return synopsis_list, paginator
def get(self): user = self.getAuthentificatedUser() forum = self.getForumInstance() page = self.request.get('page') try: page = int(page) - 1 except: page = 0 try: id = int(self.request.get('id')) #topic = Topic.get(db.Key.from_path('Topic', id)) topic = self.getTopic(id) # is this a private topic if not topic.thread.public and user is None: self.redirect('/') return except: self.redirect('/') return #topic = self.getTopics().order('-pub_date').fetch(1) #topic = topic[0] #id = topic.key().id() posts = self.getPosts(id) paginator = ObjectPaginator(posts, 10) if page >= paginator.pages or page < 0: page = paginator.pages - 1 if page >= paginator.pages - 1: next = None else: next = page + 2 if page < 1: prev = None else: prev = page template_values = { 'url' : self.createUrl(self.request.uri), 'link' : self.createLink(), 'user' : self.getNickname(), 'forum' : forum, 'topic' : topic, 'posts' : paginator.get_page(page), 'pages' : range(1, paginator.pages + 1), 'page' : page+1, 'next' : next, 'prev' : prev, } try: if self.checkMode(str(self.request.get('mode'))): path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'viewTopicAdminMode.htm')) self.response.out.write(template.render(path, template_values)) return except: pass path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'viewTopic.htm')) self.response.out.write(template.render(path, template_values))
def filtered_kwips_page(request,user_login,year,month=0,day=0,hour=0,serial=0,filter_by='day',with_reply_box=False): is_single = False paginate_by = 10 dict = details_for_kwips_page(request,user_login) month_in_words = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'] i=1 for mon in month_in_words: if month==mon: month=i i=i+1 #getting all accounts for user accounts = Account.objects.filter(user=dict['user'],status=1) if accounts: accounts_list_in_csv = queryset_to_csv(accounts,'account') if filter_by=='year': quips = Quip.objects.filter(account__in=accounts_list_in_csv,created_at__year=int(year)).order_by('-created_at') elif filter_by=='month': quips = Quip.objects.filter(account__in=accounts_list_in_csv,created_at__year=int(year),created_at__month=int(month)).order_by('-created_at') elif filter_by=='date': quips = Quip.objects.filter(account__in=accounts_list_in_csv,created_at__year=int(year),created_at__month=int(month),created_at__day=int(day)).order_by('-created_at') elif filter_by=='hour': quips = quip_for_a_time(dict['user'],filter_by,year,month,day,hour) elif filter_by=='minute': minute=hour[2]+hour[3] hour = hour[0]+hour[1] quips = quip_for_a_time(dict['user'],filter_by,year,month,day,int(hour),int(minute)) elif filter_by=='second': second=hour[4]+hour[5] minute=hour[2]+hour[3] hour = hour[0]+hour[1] quips = quip_for_a_time(dict['user'],filter_by,year,month,day,int(hour),int(minute),int(second)) if len(quips)==1: is_single=True elif filter_by=='single': second=hour[4]+hour[5] minute=hour[2]+hour[3] hour = hour[0]+hour[1] quipsnow = quip_for_a_time(dict['user'],filter_by,year,month,day,int(hour),int(minute),int(second)) is_single=True for q in quipsnow: quips = q.quips_on_same_time_serial(int(serial)) #break commented by MD paginator = ObjectPaginator(quips, paginate_by) page = int(request.GET.get('page',0)) quips = paginator.get_page(page) return render_to_response('mypage.html', {'is_paginated': paginator.pages > 1, 'results_per_page': paginate_by, 'has_next': paginator.has_next_page(page), 'has_previous': paginator.has_previous_page(page), 'page': page + 1, 'next': page + 1, 'previous': page - 1, 'pages': paginator.pages, 'is_following': dict['is_following'],'is_following_on_im': dict['is_following_on_im'], 'hits' : paginator.hits, 'login': user_login,'user_profile': dict['user_profile'],'quips': quips,'is_receiver_following':dict['is_receiver_following'], 'users_followees': dict['users_followees'], 'users_followers': dict['users_followers'], 'profile_for_display': dict['profile_for_display'], 'followees_count':dict['followees_count'], 'followers_count':dict['followers_count'],'displayname': dict['displayname'],'favs_count':dict['favs_count'], 'quips_for': 'self','with_reply_box':with_reply_box,'is_single':is_single, 'kwip_count':kwip_count(dict['user']),'comment_count':comment_count(dict['user'])},context_instance=template.RequestContext(request))
def comments(request, page): paginator = ObjectPaginator(Comments.objects.all(), 10) comments = paginator.get_page(page) template_parms = {'comment_list': comments, 'comments': True} if paginator.has_next_page(page): template_parms['next'] = True if paginator.has_previous_page(page): template_parms['prev'] = True return render_to_response('comments.html', template_parms)
def paginate(obj, page): p = ObjectPaginator( obj, PAGE_ELEMENTS ) try: obj_list = p.get_page(page - 1) except InvalidPage: obj_list = [] return (obj_list, p)
def get(self,page): #rpc = db.create_rpc(deadline=10, read_policy=db.EVENTUAL_CONSISTENCY) paginator = ObjectPaginator(db.GqlQuery('SELECT * FROM BlogPostModel ORDER BY created DESC'),10) try: blogposts = paginator.get_page(page) self.response.out.write(simplejson.dumps([p.to_dict() for p in blogposts])) except: self.error(404)
def changes(request, asset_type=None, asset_id=None, current_user=True, page_number=0, num_per_page=10): """Return a paginated list of recent asset changes, filtered in the following ways: - If 'asset_type' and 'asset_id' are supplied, this limits the changes to those from a single asset. - If 'current_user' is set, this only shows changes to objects that are owned by the currently logged-in user. This returns a JSON result which is used by client-side pagination code. """ changes = models.AssetChangeset.objects.all() if asset_id is not None: changes = changes.filter( content_type=ContentType.objects.get_for_model( get_asset_by_type(asset_type)), object_id=int(asset_id), ) if current_user: changes = changes.extra( tables=["accounts_userasset"], where=[ "accounts_userasset.content_type_id = accounts_assetchangeset.content_type_id", "accounts_userasset.object_id = accounts_assetchangeset.object_id", "accounts_userasset.user_id = %d" % request.user.id ], ) paginator = ObjectPaginator(changes.order_by('-id'), num_per_page=num_per_page, orphans=num_per_page / 2) return { 'remaining': paginator.hits - paginator.last_on_page(page_number), 'html': smart_unicode( loader.render_to_string( 'accounts/asset_changes.html', RequestContext( request, { 'changesets': paginator.get_page(page_number), 'show_asset_name': asset_id is None, }))), }
def frontpage(request, pagenum = 0): posts, pagedata = init() max_single_posts_on_page = 5 pages = ObjectPaginator(posts, max_single_posts_on_page) viewpage = pages.get_page(pagenum) pagedata['post_list'] = viewpage pagedata.update({'subtitle': '', 'pages': pages.pages, 'pagenum': int(pagenum), 'page_list': range(0, pages.pages) }) return render_to_response( 'listpage.xhtml', pagedata)
def _display_common(response_dict, page, p): paginator = ObjectPaginator(p, 20, 2) p = paginator.get_page(page) if not p: raise Http404 response_dict['object_list'] = p response_dict['page'] = page if paginator.has_next_page(page): response_dict['next'] = page+1 if paginator.has_previous_page(page): response_dict['prev'] = page-1 return response_dict
def list(self, request, queryset, page=None): """ Renders a list of model objects to HttpResponse. """ template_name = '%s/%s_list.html' % (self.template_dir, queryset.model._meta.module_name) if self.paginate_by: paginator = ObjectPaginator(queryset, self.paginate_by) if not page: page = request.GET.get('page', 1) try: page = int(page) object_list = paginator.get_page(page - 1) except (InvalidPage, ValueError): if page == 1 and self.allow_empty: object_list = [] else: raise Http404 c = RequestContext( request, { '%s_list' % self.template_object_name: object_list, 'is_paginated': paginator.pages > 1, 'results_per_page': self.paginate_by, 'has_next': paginator.has_next_page(page - 1), 'has_previous': paginator.has_previous_page(page - 1), 'page': page, 'next': page + 1, 'previous': page - 1, 'last_on_page': paginator.last_on_page(page - 1), 'first_on_page': paginator.first_on_page(page - 1), 'pages': paginator.pages, 'hits': paginator.hits, }, self.context_processors) else: object_list = queryset c = RequestContext( request, { '%s_list' % self.template_object_name: object_list, 'is_paginated': False }, self.context_processors) if not self.allow_empty and len(queryset) == 0: raise Http404 # Hide unexposed fields for obj in object_list: self._hide_unexposed_fields(obj, self.expose_fields) c.update(self.extra_context) t = self.template_loader.get_template(template_name) return HttpResponse(t.render(c), mimetype=self.mimetype)
def home(request): """ Home Page """ pager = ObjectPaginator(Post.objects.all(), 10) pager.page = int(request.GET.get("sayfa", 1)) try: posts = pager.get_page(pager.page - 1) except: posts = None pager.url = make_url_pattern(reverse("home"), request.GET) return render_to_response("entries/home.html", { "posts" : posts, "pager" : pager }, context_instance=RequestContext(request))
def list(self, request, queryset, page=None): """ Renders a list of model objects to HttpResponse. """ template_name = '%s/%s_list.html' % (self.template_dir, queryset.model._meta.module_name) if self.paginate_by: paginator = ObjectPaginator(queryset, self.paginate_by) if not page: page = request.GET.get('page', 1) try: page = int(page) object_list = paginator.get_page(page - 1) except (InvalidPage, ValueError): if page == 1 and self.allow_empty: object_list = [] else: raise Http404 c = RequestContext(request, { '%s_list' % self.template_object_name: object_list, 'is_paginated': paginator.pages > 1, 'results_per_page': self.paginate_by, 'has_next': paginator.has_next_page(page - 1), 'has_previous': paginator.has_previous_page(page - 1), 'page': page, 'next': page + 1, 'previous': page - 1, 'last_on_page': paginator.last_on_page(page - 1), 'first_on_page': paginator.first_on_page(page - 1), 'pages': paginator.pages, 'hits' : paginator.hits, }, self.context_processors) else: object_list = queryset c = RequestContext(request, { '%s_list' % self.template_object_name: object_list, 'is_paginated': False }, self.context_processors) if not self.allow_empty and len(queryset) == 0: raise Http404 # Hide unexposed fields for obj in object_list: self._hide_unexposed_fields(obj, self.expose_fields) c.update(self.extra_context) t = self.template_loader.get_template(template_name) return HttpResponse(t.render(c), mimetype=self.mimetype)
def get_results(self, request): paginator = ObjectPaginator(self.query_set, self.lookup_opts.admin.list_per_page) # Get the number of objects, with admin filters applied. try: result_count = paginator.hits # Naked except! Because we don't have any other way of validating # "params". They might be invalid if the keyword arguments are # incorrect, or if the values are not in the correct type (which would # result in a database error). except: raise IncorrectLookupParameters # Get the total number of objects, with no admin filters applied. # Perform a slight optimization: Check to see whether any filters were # given. If not, use paginator.hits to calculate the number of objects, # because we've already done paginator.hits and the value is cached. if isinstance(self.query_set._filters, models.Q) and not self.query_set._filters.kwargs: full_result_count = result_count else: full_result_count = self.manager.count() can_show_all = result_count <= MAX_SHOW_ALL_ALLOWED multi_page = result_count > self.lookup_opts.admin.list_per_page # Get the list of objects to display on this page. if (self.show_all and can_show_all) or not multi_page: result_list = list(self.query_set) else: try: result_list = paginator.get_page(self.page_num) except InvalidPage: result_list = () #This is set to 0 if show_all_rows is false, checking of which rows to be shown #is done later in the result_list tag at which point it will calculate the correct #number of rows shown self.result_count = result_count self.full_result_count = full_result_count self.result_list = result_list self.can_show_all = can_show_all self.multi_page = multi_page self.paginator = paginator
def __init__(self, queryset, request=None, pageno=1, paginate_by=15, urlprefix='', urlnames=urlnames): if isinstance(queryset, QuerySet): self.queryset = queryset else: self.queryset = QuerysetWrapper(queryset) self.paginate_by = paginate_by self.request = request self.urlprefix = urlprefix self.urlname = urlnames self.pageno = pageno paginator = ObjectPaginator(self.queryset, paginate_by) lastpage = math.ceil(1.0 * self.queryset.count() / paginate_by) if self.request: page = self.request.GET.get('page', 1) else: page = self.pageno try: if isinstance(page, str): if not page.isdigit(): page = 'last' page = lastpage page = int(page) if page > lastpage: page = lastpage object_list = paginator.get_page(page - 1) except (InvalidPage, ValueError): object_list = [] self.is_paginated = paginator.pages > 1 self.results_per_page = paginate_by self.has_next = paginator.has_next_page(page - 1) self.has_previous = paginator.has_previous_page(page - 1) self.page = page self.next = page + 1 self.previous = page - 1 self.pages = paginator.pages self.hits = paginator.hits self.object_list = object_list
def get(self): user = self.getAuthentificatedUser() forum = self.getForumInstance() page = self.request.get('page') try: page = int(page) - 1 except: page = 0 try: id = int(self.request.get('id')) #topic = Topic.get(db.Key.from_path('Topic', id)) topic = self.getTopic(id) except: self.redirect('/') return #topic = self.getTopics().order('-pub_date').fetch(1) #topic = topic[0] #id = topic.key().id() posts = self.getPosts(id) paginator = ObjectPaginator(posts, 10) if page >= paginator.pages or page < 0: page = paginator.pages - 1 if page >= paginator.pages - 1: next = None else: next = page + 2 if page < 1: prev = None else: prev = page template_values = { 'url' : users.CreateLogoutURL(self.request.uri), 'user' : user.nickname(), 'forum' : forum, 'topic' : topic, 'posts' : paginator.get_page(page), 'pages' : range(1, paginator.pages + 1), 'page' : page+1, 'next' : next, 'prev' : prev, } path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'viewTopic.htm')) self.response.out.write(template.render(path, template_values))
def viewGallery(request): try: page = int(request.GET.get('step', '1')) - 1 except: page = 0 data = Picture.all() paginator = ObjectPaginator(data, 25) if page>=paginator.pages: page = paginator.pages - 1 params = { "pictures" : paginator.get_page(page), "steps" : range(1,paginator.pages+1), "step" : page+1 } return respond(request, 'gallery.html', params)
def main(request,fb_for='all'): if request.user.is_superuser: page = int(request.GET.get('page',0)) paginate_by = 10 if fb_for=='self': feedback = Feedback.objects.filter(user=request.user).order_by('-created_at') elif fb_for=='all': feedback = Feedback.objects.all().order_by('-created_at') paginator = ObjectPaginator(feedback, paginate_by) feedback = paginator.get_page(page) return render_to_response('fb.html', {'is_paginated': paginator.pages > 1, 'results_per_page': paginate_by, 'has_next': paginator.has_next_page(page), 'has_previous': paginator.has_previous_page(page), 'page': page + 1, 'next': page + 1, 'previous': page - 1, 'pages': paginator.pages, 'hits' : paginator.hits,'quips': feedback,'quips_for': fb_for,}, context_instance=template.RequestContext(request)) else: return HttpResponseRedirect('/'+request.user.username+'/') #sweating by still coding :)
def changes(request, asset_type=None, asset_id=None, current_user=True, page_number=0, num_per_page=10): """Return a paginated list of recent asset changes, filtered in the following ways: - If 'asset_type' and 'asset_id' are supplied, this limits the changes to those from a single asset. - If 'current_user' is set, this only shows changes to objects that are owned by the currently logged-in user. This returns a JSON result which is used by client-side pagination code. """ changes = models.AssetChangeset.objects.all() if asset_id is not None: changes = changes.filter( content_type = ContentType.objects.get_for_model(get_asset_by_type(asset_type)), object_id = int(asset_id), ) if current_user: changes = changes.extra( tables = ["accounts_userasset"], where = ["accounts_userasset.content_type_id = accounts_assetchangeset.content_type_id", "accounts_userasset.object_id = accounts_assetchangeset.object_id", "accounts_userasset.user_id = %d" % request.user.id], ) paginator = ObjectPaginator(changes.order_by('-id'), num_per_page = num_per_page, orphans = num_per_page / 2) return { 'remaining': paginator.hits - paginator.last_on_page(page_number), 'html': smart_unicode(loader.render_to_string( 'accounts/asset_changes.html', RequestContext(request, { 'changesets': paginator.get_page(page_number), 'show_asset_name': asset_id is None, }))), }
def list_texts(request, type=None): if type: obj = Text.objects.filter(type=type, is_hidden=0).order_by('-submit_date') else: obj = Text.objects.filter(type__in=[1, 2, 3, 5], is_hidden=0).order_by('-submit_date') paginator = ObjectPaginator(obj, 50) page = int(request.GET.get('page', '1')) try: texts = paginator.get_page(page - 1) except InvalidPage: texts = [] # compose page title pageTitle = cattext(type) return render_to_response('texts/texts_list.html', {'pagetitle': pageTitle, 'texts': texts, 'page': page, 'paginator': paginator, 'type': type}, context_instance=RequestContext(request))
def list(self, request, queryset, page=None): """ Renders a list of model objects to HttpResponse. """ if self.paginate_by: paginator = ObjectPaginator(queryset, self.paginate_by) if not page: page = request.GET.get('page', 1) try: page = int(page) object_list = paginator.get_page(page - 1) except (InvalidPage, ValueError): if page == 1 and self.allow_empty: object_list = [] else: return self.error(request, 404) else: object_list = list(queryset) return HttpResponse(self.render(object_list), self.mimetype)
def list(self, request, queryset, page=None): """ Renders a list of model objects to HttpResponse. """ if self.paginate_by: paginator = ObjectPaginator(queryset, self.paginate_by) if not page: page = request.GET.get('page', 1) try: page = int(page) object_list = paginator.get_page(page - 1) except (InvalidPage, ValueError): if page == 1 and self.allow_empty: object_list = [] else: return self.error(request, 404) else: object_list = list(queryset) return HttpResponse(self.render(object_list), self.mimetype)
def get_results(self, request): paginator = ObjectPaginator(self.query_set, self.lookup_opts.admin.list_per_page) # Get the number of objects, with admin filters applied. try: result_count = paginator.hits # Naked except! Because we don't have any other way of validating # "params". They might be invalid if the keyword arguments are # incorrect, or if the values are not in the correct type (which would # result in a database error). except: raise IncorrectLookupParameters # Get the total number of objects, with no admin filters applied. # Perform a slight optimization: Check to see whether any filters were # given. If not, use paginator.hits to calculate the number of objects, # because we've already done paginator.hits and the value is cached. if isinstance(self.query_set._filters, models.Q) and not self.query_set._filters.kwargs: full_result_count = result_count else: full_result_count = self.manager.count() can_show_all = result_count <= MAX_SHOW_ALL_ALLOWED multi_page = result_count > self.lookup_opts.admin.list_per_page # Get the list of objects to display on this page. if (self.show_all and can_show_all) or not multi_page: result_list = list(self.query_set) else: try: result_list = paginator.get_page(self.page_num) except InvalidPage: result_list = () self.result_count = result_count self.full_result_count = full_result_count self.result_list = result_list self.can_show_all = can_show_all self.multi_page = multi_page self.paginator = paginator
def category_detail(request, slug): """ Category detail page """ category = get_object_or_404(Category.objects, slug=slug) pager = ObjectPaginator(Post.objects.filter(category=category), 10) pager.page = int(request.GET.get("sayfa", 1)) try: posts = pager.get_page(pager.page - 1) except: posts = None pager.url = make_url_pattern(reverse("category_detail", kwargs={"slug": slug}), request.GET) return render_to_response("entries/category_detail.html", { "category" : category, "posts" : posts, "pager" : pager }, context_instance=RequestContext(request))
def generatePagination(baseUrl, attrs, objects, pageSize): """generates division to pages of objects :Parameters: baseUrl: base url where pages should point attrs: attributes to put to other page links (should contain current page number) objects: all objects to split to pages pageSize: number of objects to display on one page :Return: tuple (htmlCode, objectSubset): htmlCode contains links to other pages and current page num objectSubset is subset of objects for current page """ html = "" try: page = int(attrs['page']) - 1 except KeyError: page = 0 baseAddr = generateAddress(baseUrl, attrs, 'page') pagination = ObjectPaginator(objects, pageSize) if page < 0 or page >= pagination.pages: page = 0 html += "page " + str(page + 1) + " of " + str(pagination.pages) + "<br/>" html += "pages: " for pgnum in pagination.page_range: html += " " if pgnum -1 == page: html += str(pgnum) else: html += "<a href=\""+ baseAddr + "page=" + str(pgnum) + "&\">" + \ str(pgnum) + "</a>" html += " " return (html, pagination.get_page(page))
def get(self): user = users.get_current_user() if not user: return self.redirect('/admin/index') cookie = SimpleCookie(os.environ.get('HTTP_COOKIE', '')) #############PICTURE####################### picturepage = self.request.get('picturepage') if picturepage == '': if cookie.has_key('picturepage'): picturepage = cookie['picturepage'].value.decode('utf-8') else: cookie['picturepage'] = picturepage.encode('utf-8') cookie['picturepage']['expires'] = 3600 try: picturepage = int(picturepage) - 1 except: picturepage = 0 userid = self.request.get('userid') datas = User.get_by_id(long(userid)) params = {'datas': datas} paginator = ObjectPaginator(datas.picture_set, PICTUREPAGE) if picturepage >= paginator.pages: picturepage = paginator.pages - 1 ##############PICTURE_END##################### ##############ALBUM######################### albumpage = self.request.get('albumpage') if albumpage == '': if cookie.has_key('albumpage'): albumpage = cookie['albumpage'].value.decode('utf-8') else: cookie['albumpage'] = albumpage.encode('utf-8') cookie['albumpage']['expires'] = 3600 print cookie.output() try: albumpage = int(albumpage) - 1 except: albumpage = 0 albumpaginator = ObjectPaginator(datas.album_set, ALBUMPICTURE) if albumpage >= albumpaginator.pages: albumpage = albumpaginator.pages - 1 params = { "datas": paginator.get_page(picturepage), "picturepages": range(1, paginator.pages + 1), "picturepage": picturepage + 1, "userid": datas, "albumdatas": albumpaginator.get_page(albumpage), "albumpages": range(1, albumpaginator.pages + 1), "albumpage": albumpage + 1 } fpath = os.path.join(os.path.dirname(__file__), 'template/admin/user', 'showalbum.html') html = template.render(fpath, params) self.response.out.write(html) return
def get(self): self.session = Session() if CheckAuth(self) is False: return DoAuth(self, '/writer/overview') site_domain = Datum.get('site_domain') site_domain_sync = Datum.get('site_domain_sync') site_name = Datum.get('site_name') site_author = Datum.get('site_author') site_slogan = Datum.get('site_slogan') site_analytics = Datum.get('site_analytics') if site_domain is None: site_domain = os.environ['HTTP_HOST'] Datum.set('site_domain', os.environ['HTTP_HOST']) if site_domain_sync is None: site_domain_sync = os.environ['HTTP_HOST'] Datum.set('site_domain_sync', os.environ['HTTP_HOST']) articles = memcache.get('writer_articles') if articles is None: articles = Article.all().order('-created') memcache.set('writer_articles', articles, 86400) paginator = ObjectPaginator(articles, PAGE_SIZE) try: page = int(self.request.get('page', 0)) articles = paginator.get_page(page) except InvalidPage: articles = paginator.get_page(int(paginator.pages - 1)) if paginator.pages > 1: is_paginated = True else: is_paginated = False if site_domain is None or site_name is None or site_author is None: site_configured = False else: site_configured = True if is_paginated: self.session['page'] = page urls = memcache.get('writer_urls') if urls is None: everything = Article.all().order('-title_url') urls = [] for article in everything: urls.append(article.title_url) memcache.set('writer_urls', urls, 86400) template_values = { 'site_configured': site_configured, 'is_paginated': is_paginated, 'page_size': PAGE_SIZE, 'page_has_next': paginator.has_next_page(page), 'page_has_previous': paginator.has_previous_page(page), 'page': page, 'next': page + 1, 'previous': page - 1, 'pages': paginator.pages, 'articles': articles, 'articles_total': len(articles), 'page_range': range(0, paginator.pages), 'urls': urls } if site_analytics is not None: template_values['site_analytics'] = site_analytics if site_domain_sync is None: q = site_domain else: q = site_domain + ' OR ' + site_domain_sync mentions_web = memcache.get('mentions_web') if mentions_web is None: try: mentions_web = feedparser.parse( 'http://blogsearch.google.com/blogsearch_feeds?hl=en&q=' + urllib.quote('link:' + Datum.get('site_domain')) + '&ie=utf-8&num=10&output=atom') memcache.add('mentions_web', mentions_web, 600) except: mentions_web = None if mentions_web is not None: template_values['mentions_web'] = mentions_web.entries mentions_twitter = memcache.get('mentions_twitter') if mentions_twitter is None: try: result = urlfetch.fetch(TWITTER_API_ROOT + 'search.json?q=' + urllib.quote(q)) if result.status_code == 200: mentions_twitter = simplejson.loads(result.content) memcache.add('mentions_twitter', mentions_twitter, 600) except: mentions_twitter = None if mentions_twitter is not None: if len(mentions_twitter['results']) > 0: template_values['mentions_twitter'] = mentions_twitter[ 'results'] template_values['system_version'] = VERSION if 'message' in self.session: template_values['message'] = self.session['message'] del self.session['message'] path = os.path.join(os.path.dirname(__file__), 'tpl', 'writer', 'overview.html') self.response.out.write(template.render(path, template_values))
def get(self): try: user = users.get_current_user() formList = [ 'searchValue', 'prefecture', 'line', 'station', 'category', 'hicategory', 'searchflg' ] formData={} cnt = 0 cateFlg = 0 noneFlg = 0 searchFlg = 0 stationFlg = 0 for roopList in formList: if self.request.get(roopList) !="": cnt += 1 formData[roopList] = self.request.get(roopList) if formData["category"] =="": if formData["hicategory"] != "": formData["category"] = formData["hicategory"] cookie = SimpleCookie(os.environ.get('HTTP_COOKIE', '')) if formData["searchflg"] == "1": cookie["searchValue"]="" cookie["prefecture"]="" cookie["line"]="" cookie["station"]="" if formData["searchValue"] != "": cookie["searchValue"] = formData["searchValue"].encode('utf-8') cookie['searchValue']['expires'] = 3600 else: if cookie.has_key("searchValue"): formData["searchValue"] = cookie["searchValue"].value.decode('utf-8') if formData["prefecture"] != "": cookie["prefecture"] = formData["prefecture"].encode('utf-8') cookie["prefecture"]["expires"] = 3600 else: if cookie.has_key("prefecture"): formData["prefecture"] = cookie["prefecture"].value.decode('utf-8') if formData["line"] != "": cookie["line"] = formData["line"].encode('utf-8') cookie["line"]["expires"] = 3600 else: if cookie.has_key("line"): formData["line"] = cookie["line"].value.decode('utf-8') if formData["station"] != "": cookie["station"] = formData["station"].encode('utf-8') cookie["station"]["expires"] = 3600 else: if cookie.has_key("station"): formData["station"] = cookie["station"].value.decode('utf-8') print cookie.output() #Defaulut todayTime = str(date.today()) yesterdayTime = date.today()-timedelta(1) AlbumDatas = list() if formData["searchValue"] == "" and formData["prefecture"] == "" and formData["line"] == "" and formData["station"] == "": return self.redirect('/index') else: validataKey = list() searchlist = list() if formData["searchValue"] != "": searchlist2 = formData['searchValue'].split(' ') for sc in searchlist2: if sc!='': searchlist.append(sc) if formData["prefecture"] !="": prefectureData = Prefecture.gql("WHERE prefecture_name = :1", formData["prefecture"]) for pd in prefectureData: if pd.prefecture_number != 1: if len(pd.prefecture_name) == 3: prefecture = pd.prefecture_name[0:2] if len(pd.prefecture_name)== 4: prefecture = pd.prefecture_name[0:3] searchlist.append(prefecture) if formData["line"] !="" and formData["station"] =="": searchlist.append(formData["line"]) if formData["station"] !="": searchlist.append(formData["station"]) cnt = len(searchlist) if cnt == 1: gqlAlbumDatas = Album.gql("WHERE search_index =:1", searchlist[0]) else: i = 0 searchVal = "" sqlString = "" slList = list() for sl in searchlist: i+=1 if i==1: sqlString = "search_index =:"+str(i) else: sqlString += " AND search_index =:"+str(i) slList.append(sl) if cnt == 2: gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1]) elif cnt == 3: gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2]) elif cnt == 4: gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2],slList[3]) elif cnt == 5: gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2],slList[3],slList[4]) elif cnt == 6: gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2],slList[3],slList[4],slList[5]) elif cnt == 7: gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2],slList[3],slList[4],slList[5],slList[6]) elif cnt == 8: gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2],slList[3],slList[4],slList[5],slList[6],slList[7]) elif cnt >= 9: gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2],slList[3],slList[4],slList[5],slList[6],slList[7],slList[8]) elif cnt >= 10: gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2],slList[3],slList[4],slList[5],slList[6],slList[7],slList[8],slList[9]) for AlbumData in gqlAlbumDatas: AlbumDatas.append(AlbumData) if formData["category"] != "" or formData["category"] == "populer": filterDatas = list() if formData["category"] =="today": for data in AlbumDatas: strTime = "" strTime = str(data.updateDate) if strTime[0:10] == todayTime: filterDatas.append(data) if formData["category"] =="spring": for data in AlbumDatas: if data.season == 2: filterDatas.append(data) elif formData["category"] =="summer": for data in AlbumDatas: if data.season == 3: filterDatas.append(data) elif formData["category"] =="fall": for data in AlbumDatas: if data.season == 4: filterDatas.append(data) elif formData["category"] =="winter": for data in AlbumDatas: if data.season == 5: filterDatas.append(data) elif formData["category"] =="recentPopuler": kako = date.today()-timedelta(30) for data in AlbumDatas: if data.updateDate > kako: filterDatas.append(data) AlbumDatas = list() AlbumDatas = filterDatas datas = list() for AlbumData in AlbumDatas: if AlbumData.user.name is not None: if AlbumData.user.name !="": AlbumData.user.nickname = AlbumData.user.name if AlbumData.picture_counter !=0: PcaDatas = PictureConnectAlbum.gql("WHERE album = :1 ORDER BY album", AlbumData) pictureid = 0; for PcaData in PcaDatas: try: PictureDatas = PcaData.picture pictureid = int(PictureDatas.key().id()) if(pictureid != 0): break except: pictureid=0 if pictureid != 0: AlbumData.pictureid = pictureid datas.append(AlbumData) strList = list() for data in datas: if len(data.recital) > 22: da = data.recital[0:22] da +="..." data.subrecital = da if len(data.title) > 8: da2 = data.title[0:8] da2 +="..." data.subtitle = da2 datas.sort(key=operator.attrgetter('watch_counter')) datas.reverse() page = self.request.get("page") try: page = int(page) - 1 except: page = 0 albumCount = len(datas) pagerFlg = 0 if albumCount > PAGE: pagerFlg = 1; lastPage = int(math.ceil(float(albumCount)/PAGE)) if page > lastPage: page = lastPage paginator = ObjectPaginator(datas,PAGE) if page>=paginator.pages: page = paginator.pages - 1 if user is not None: loginFlg = 1 #pager #now page picturepage+1 #last page paginator.pages+1 page1 = 1 if page+1 > 2: page1 = page+1-1 elif page+1 > 3: page1 = page+1-2 if page+1 == lastPage+1: page1 = page1-3 elif page == lastPage+1: page1 = page1-2 if page1 < 2: page1 = 2 pages = range(page1-1,lastPage+1) ################selext box###################### PreDatas = Prefecture.all() prelist = list() lineDatas = list() StationDatas = list() for pd in PreDatas: prelist.append(pd) prelist.sort(key=operator.attrgetter("prefecture_number")) if formData["prefecture"] !="": lineDatas = self.createLine(formData["prefecture"]) if formData["line"] !="": StationDatas = self.createStation(formData["line"]) #################create login####################### user = users.get_current_user() loginFlg = "" user_top_link = "" logout_link = "" if user is not None: loginFlg = 1 logout_link = users.create_logout_url(PROTOCOLHTTP+DOMAIN+"/index") else: user_top_link = users.create_login_url(PROTOCOLHTTPS+DOMAIN+"/user") #################create map####################### prefectureData = Prefecture.gql("WHERE prefecture_number = :1 order by prefecture_number", 26) for pd in prefectureData: if pd.prefecture_number != 1: if len(pd.prefecture_name) == 3: prefecture = pd.prefecture_name[0:2] if len(pd.prefecture_name)== 4: prefecture = pd.prefecture_name[0:3] gqlAlbumDatas = Album.gql("WHERE search_index =:1 limit 0, 100", prefecture) sortList = list() for AlbumData in gqlAlbumDatas: try: if AlbumData.picture_counter > 0: sortList.append(AlbumData) except: continue sortList.sort(key=operator.attrgetter('watch_counter')) AlbumDatas = list() AlbumDatas2 = list() for AlbumData in sortList: if AlbumData.latitude is not None and AlbumData.longitude is not None: AlbumDatas2.append(AlbumData) params = { "datas" : paginator.get_page(page), "pages" : pages, "page" : page+1, "prev" : page, "next" : page+2, "pagerFlg" : pagerFlg, "lastpage" : lastPage, "category" : formData["category"], "searchValue" : formData["searchValue"], "prefecture" : formData["prefecture"], "line" : formData["line"], "station" : formData["station"], "hicategory" : formData["hicategory"], "searchflg" : formData["searchflg"], "AlbumDatas" : AlbumDatas2, "PreDatas" : prelist, "lineDatas" : lineDatas, "user_top_link" : user_top_link, "logout_link" : logout_link, "loginFlg" : loginFlg, "StationDatas" : StationDatas } fpath = os.path.join(os.path.dirname(__file__),'template/user','indexsearch.html') html = template.render(fpath,params) self.response.out.write(html) except: self.errorFunc()
def object_list(request, queryset, paginate_by=None, page=None, allow_empty=False, template_name=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): """ Generic list of objects. Templates: ``<app_label>/<model_name>_list.html`` Context: object_list list of objects is_paginated are the results paginated? results_per_page number of objects per page (if paginated) has_next is there a next page? has_previous is there a prev page? page the current page next the next page previous the previous page pages number of pages, total hits number of objects, total last_on_page the result number of the last of object in the object_list (1-indexed) first_on_page the result number of the first object in the object_list (1-indexed) """ if extra_context is None: extra_context = {} queryset = queryset._clone() if paginate_by: paginator = ObjectPaginator(queryset, paginate_by) if not page: page = request.GET.get('page', 1) try: page = int(page) object_list = paginator.get_page(page - 1) except (InvalidPage, ValueError): if page == 1 and allow_empty: object_list = [] else: raise Http404 c = RequestContext( request, { '%s_list' % template_object_name: object_list, 'is_paginated': paginator.pages > 1, 'results_per_page': paginate_by, 'has_next': paginator.has_next_page(page - 1), 'has_previous': paginator.has_previous_page(page - 1), 'page': page, 'next': page + 1, 'previous': page - 1, 'last_on_page': paginator.last_on_page(page - 1), 'first_on_page': paginator.first_on_page(page - 1), 'pages': paginator.pages, 'hits': paginator.hits, }, context_processors) else: c = RequestContext(request, { '%s_list' % template_object_name: queryset, 'is_paginated': False }, context_processors) if not allow_empty and len(queryset) == 0: raise Http404 for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value if not template_name: model = queryset.model template_name = "%s/%s_list.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) return HttpResponse(t.render(c), mimetype=mimetype)
def get(self): user = users.get_current_user() if user is None: return self.redirect('/index') else: logout_link = users.create_logout_url(PROTOCOLHTTP + DOMAIN + "/index") page = self.request.get('page') zoomFlg = self.request.get('zoomFlg') searchLabel = self.request.get('searchLabel') picturHandlerePage = self.request.get('picturHandlerePage') delFlg = self.request.get('delFlg') cookie = SimpleCookie(os.environ.get('HTTP_COOKIE', '')) if delFlg != "1": if searchLabel != "": cookie['picturHandlerePage'] = "" cookie['searchLabel'] = searchLabel.encode('utf-8') cookie['searchLabel']['expires'] = 3600 print cookie.output() else: if cookie.has_key('searchLabel'): searchLabel = cookie['searchLabel'].value.decode('utf-8') else: searchLabel = "" picturHandlerePage = "" cookie['searchLabel'] = "" cookie['picturHandlerePage'] = "" print cookie.output() #############PICTURE####################### if picturHandlerePage == '': if cookie.has_key('picturHandlerePage'): picturHandlerePage = cookie['picturHandlerePage'].value.decode( 'utf-8') else: cookie['picturHandlerePage'] = picturHandlerePage.encode('utf-8') cookie['picturHandlerePage']['expires'] = 3600 print cookie.output() try: picturHandlerePage = int(picturHandlerePage) - 1 except: picturHandlerePage = 0 email = user.email() userData = db.GqlQuery("SELECT * FROM User WHERE email='" + email + "'") for user in userData: userid = user.key().id() userDatas = User.get_by_id(long(userid)) userPictureDatas = userDatas.picture_set datas = list() keyList = list() for PictureData in userPictureDatas: keyList.append(PictureData.key().id()) if searchLabel != "": PictureDatas = Picture.gql("WHERE label =:1", searchLabel) for PictureData in PictureDatas: if PictureData.key().id() in keyList: datas.append(PictureData) else: for upd in userPictureDatas: datas.append(upd) datas.sort(key=operator.attrgetter('registerDate')) datas.reverse() pictureCount = len(datas) pagerFlg = 0 if pictureCount > PAGE: pagerFlg = 1 lastPage = int(math.ceil(float(pictureCount) / PAGE)) if picturHandlerePage > lastPage: picturHandlerePage = lastPage #pager #now page picturepage+1 #last page paginator.pages+1 page1 = 1 if picturHandlerePage + 1 > 2: page1 = picturHandlerePage + 1 - 1 elif picturHandlerePage + 1 > 3: page1 = picturHandlerePage + 1 - 2 if picturHandlerePage + 1 == lastPage + 1: page1 = page1 - 3 elif picturHandlerePage == lastPage + 1: page1 = page1 - 2 if page1 < 2: page1 = 2 pages = range(page1 - 1, lastPage + 1) paginator = ObjectPaginator(datas, PAGE) if picturHandlerePage >= paginator.pages: picturHandlerePage = paginator.pages - 1 if user: loginFlg = 1 params = { "datas": paginator.get_page(picturHandlerePage), "pages": pages, "page": picturHandlerePage + 1, "prev": picturHandlerePage, "next": picturHandlerePage + 2, "pagerFlg": pagerFlg, "lastpage": lastPage, 'zoomFlg': zoomFlg, 'searchLabel': searchLabel, 'loginFlg': loginFlg, 'logout_link': logout_link } fpath = os.path.join(os.path.dirname(__file__), 'template/user/picture', 'list.html') html = template.render(fpath, params) self.response.out.write(html) return