def admin_posts(page=1): # Create cursor cur = mysql.connection.cursor() # Get posts result = cur.execute( "SELECT p.id, p.post_title, p.post_author, p.post_content, p.post_date, p.post_modified, p.post_count, t.name AS category FROM posts p LEFT JOIN terms t ON p.post_parent = t.term_id ORDER BY p.id DESC" ) if result > 0: posts = cur.fetchall() # Each page size page_size = 15 # Paginated posts list posts_cut = list(paginate(posts, page_size)) # Page number list page_list = list(range(1, len(posts_cut) + 1)) # Close connection cur.close() if page > 0 and page < len(posts_cut) + 1: return render_template('admin/admin_posts.html', posts=posts_cut[page - 1], page=page, page_list=page_list) else: return redirect(url_for('.admin_posts')) else: msg = 'No posts Found.' posts = '' return render_template('admin/admin_posts.html', msg=msg, posts=posts)
def posts(page=1, category='default'): # Create cursor cur = mysql.connection.cursor() # Get posts res1 = cur.execute("SELECT p.id, p.post_title, p.post_author, p.post_content, p.post_date, p.post_modified, p.post_count, t.name AS category FROM posts p LEFT JOIN terms t ON p.post_parent = t.term_id WHERE t.alias=%s ORDER BY p.id DESC", [category]) posts = cur.fetchall() res2 = cur.execute("SELECT * FROM terms") terms = cur.fetchall() # Close connection cur.close() if res1 > 0: # Each page size page_size = 12 # Paginated posts list posts_cut = list(paginate(posts, page_size)) # Page number list page_list = list(range(1, len(posts_cut) + 1)) if page > 0 and page < len(posts_cut) + 1: return render_template('base/posts.html', posts=posts_cut[page - 1], page=page, page_list=page_list, terms=terms, category=category) else: return redirect(url_for('.posts')) else: msg = 'No posts Found.' posts = '' return render_template('base/posts.html', msg=msg, posts=posts, terms=terms, category=category)
def thesis_list(request, id, slug): conference = get_object_or_404(Conference, pk=id) theses = conference.thesis_set.all() form = ThesisFilterForm() search_form = SearchForm(search_text='Прізвище автора або назва статті') sort_param = None q = request.GET.get('q', '') thesis_message = '' if q: search_params = ('title', 'author__participant__user__lastname') theses = search_objects(q, theses, search_params, sort_param) store(request, q) section = request.GET.get('section', '') if section: form = ThesisFilterForm(request.GET) if form.is_valid(): if request.GET.get('section') != 'all': theses = theses.filter(section=request.GET.get('section')) number_of_search_result = str(len(theses)) if len(number_of_search_result) == 2 and number_of_search_result.startswith('1'): thesis_message = 'доповідей' else: for i in thesis_message_dict.keys(): if number_of_search_result[-1] in i: thesis_message = thesis_message_dict[i] context = paginate(theses, 4, request, {'theses': theses}, var_name='theses') context['conference'] = conference context['form'] = form context['search_form'] = search_form context['q'] = q context['section'] = section context['number_of_search_results'] = number_of_search_result context['thesis_message'] = thesis_message return render(request, 'conference_app/thesis_list.html', context)
def admin_users(page=1): # Create cursor cur = mysql.connection.cursor() # Get posts result = cur.execute( "SELECT u.id, u.username, u.fullname, u.email, u.register_date, u.user_status, r.role FROM users u LEFT JOIN roles r ON u.user_role = r.id ORDER BY u.id DESC" ) if result > 0: users = cur.fetchall() # Each page size page_size = 15 # Paginated posts list users_cut = list(paginate(users, page_size)) # Page number list page_list = list(range(1, len(users_cut) + 1)) # Close connection cur.close() if page > 0 and page < len(users_cut) + 1: return render_template('admin/admin_users.html', users=users_cut[page - 1], page=page, page_list=page_list) else: return redirect(url_for('.admin_users'))
def get(self, request, **kwargs): """Function override due to adding pagination and search.""" url_without_parameters = str(request.get_full_path()).split('?')[0] url_parameter_q = request.GET.get('q') if url_parameter_q: ctx = { 'patients': self.get_queryset().order_by('-date_selected').filter( last_name__icontains=url_parameter_q), } else: ctx = { 'patients': self.get_queryset().order_by('-date_selected'), } paginated_patients = paginate(request, ctx['patients'], 10) ctx = { 'patients': paginated_patients, 'endpoint': url_without_parameters } if request.is_ajax(): html = render_to_string( template_name= 'office_panel/patient/patients_results_partial.html', context=ctx) data_dict = {"html_from_view": html} return JsonResponse(data=data_dict, safe=False) return render(request, self.template_name, ctx)
def get(self, request): """Function override due to adding pagination and search.""" url_without_parameters = str(request.get_full_path()).split('?')[0] url_parameter_q = request.GET.get('q') if url_parameter_q: ctx = { 'medical_histories': MedicalHistory.objects.filter( owner=self.request.user.id, patient__last_name__icontains=url_parameter_q).order_by( '-date_selected'), } else: ctx = { 'medical_histories': MedicalHistory.objects.filter( owner=self.request.user.id).order_by('-date_selected'), } paginated_medical_histories = paginate(request, ctx['medical_histories'], 10) ctx = { 'medical_histories': paginated_medical_histories, 'endpoint': url_without_parameters } if request.is_ajax(): html = render_to_string( template_name= 'medical_history/office/medical_history_results_partial.html', context=ctx) data_dict = {"html_from_view": html} return JsonResponse(data=data_dict, safe=False) return render(request, self.template_name, ctx)
def get_context_data(self, **kwargs): projects = super().get_queryset() context = paginate(projects, 10, self.request, {'projects': projects}, var_name='projects') return context
def get(self, request): """Method override due to adding pagination and filtering.""" url_without_parameters = str(request.get_full_path()).split('?')[0] url_parameter_q = request.GET.get('q') if url_parameter_q: ctx = { 'offices': self.get_queryset().filter(name__icontains=url_parameter_q) } else: ctx = { 'offices': self.get_queryset(), } paginated_offices = paginate(request, ctx['offices'], 10) ctx = { 'offices': paginated_offices, 'endpoint': url_without_parameters } if request.is_ajax(): html = render_to_string( template_name='patient_panel/offices_results_partial.html', context=ctx) data_dict = {"html_from_view": html} return JsonResponse(data=data_dict, safe=False) return render(request, self.template_name, ctx)
def get(self, request): """Function override due to adding pagination.""" services = Service.objects.filter(office=self.request.user.id) paginated_services = paginate(request, services, 10) ctx = { 'services': paginated_services, } return render(request, self.template_name, ctx)
def results(request, query): queryset = get_photo_queryset(query=query) paginator, queryset = paginate(request, queryset, settings.PHOTOS_PER_PAGE) context = { 'query': query, 'paginator': paginator, 'photo_list': queryset, 'back_link': {'url': reverse('search'), 'title': 'Search'} } return render(request, 'photos/search_results.html', context)
def detail(request, pk): person = get_object_or_404(Person, pk=pk) paginator, queryset = paginate( request, get_photo_queryset(person=person), settings.PHOTOS_PER_PAGE) context = { 'person': person, 'paginator': paginator, 'photo_list': queryset, 'back_link': {'url': reverse('people'), 'title': _('People')} } return render(request, 'photos/person_detail.html', context)
def detail(request, pk): location = get_object_or_404(Location, pk=pk) paginator, queryset = paginate( request, location.album_set.all(), settings.PHOTOS_PER_PAGE) context = { 'location': location, 'paginator': paginator, 'album_list': queryset, 'back_link': {'url': reverse('locations'), 'title': _('Locations')} } return render(request, 'photos/location_detail.html', context)
def get_context_data(self, **kwargs): news = self.get_queryset() tags = [] for n in news: if n.tags: tags.extend([tag.strip() for tag in n.tags.split(',')]) context = paginate(news, 10, self.request, {'news': news}, var_name='news') context['tags'] = list(set(tags)) return context
def detail(request, pk, **kwargs): album = get_object_or_404(Album, pk=pk) paginator, queryset = paginate( request, get_photo_queryset(album=album), settings.PHOTOS_PER_PAGE) context = { 'location_pk': kwargs.get('location_pk'), 'album': album, 'paginator': paginator, 'photo_list': queryset, 'back_link': get_back_link(request, album, **kwargs) } return render(request, 'photos/album_detail.html', context)
def admin_comments(page=1): # Create cursor cur = mysql.connection.cursor() # Get posts result = cur.execute( "SELECT c.id, c.comm_author, c.comm_content, c.comm_date, c.comm_modified, c.comm_post, p.post_title FROM comments c, posts p WHERE c.comm_post = p.id ORDER BY c.id DESC" ) comments = cur.fetchall() if result > 0: # Each page size page_size = 15 # Paginated posts list comments_cut = list(paginate(comments, page_size)) # Page number list page_list = list(range(1, len(comments_cut) + 1)) # Close connection cur.close() if page > 0 and page < len(comments_cut) + 1: return render_template('admin/admin_comments.html', comments=comments_cut[page - 1], page=page, page_list=page_list) else: return redirect(url_for('.admin_comments')) else: msg = 'No comments Found.' comments = '' page_list = [1] return render_template('admin/admin_comments.html', comments=comments, page=page, page_list=page_list, msg=msg)
def test_paginate(self): """ Test that our custom paginate() method works properly. """ factory = RequestFactory() articles = self.get_article_set() url = '/dummy/page' for test in self.get_scenarios(): params, page, prev_params, next_params, results = test request = factory.get(url + '?' + QueryDict(params).urlencode()) paginator, queryset = paginate(request, articles, 3) self.assertEqual(paginator.this_page.number, page) self.assertEqual(queryset, results) if next_params: next_dict = QueryDict(next_params) pag_dict = QueryDict(urlparse(paginator.next_url).query) self.assertEqual(next_dict, pag_dict) if prev_params: prev_dict = QueryDict(prev_params) pag_dict = QueryDict(urlparse(paginator.previous_url).query) self.assertEqual(prev_dict, pag_dict) # there is no page 4 so it throws an error request = factory.get('/dummy?p=4') with self.assertRaises(Http404): paginate(request, articles, 3) # allow empty works request = factory.get('/dummy') paginator, queryset = paginate(request, [], 3, allow_empty=True) self.assertEqual(queryset, []) # don't allow empty request = factory.get('/dummy') with self.assertRaises(Http404): paginate(request, [], 3, allow_empty=False)
def admin_category(page=1): form = CategoryForm(request.form) action = 'Add a new category' # Create cursor cur = mysql.connection.cursor() # Get category res1 = cur.execute("SELECT * FROM terms order by term_id desc") db_terms = cur.fetchall() res2 = cur.execute("SELECT alias FROM terms order by term_id desc") db_terms_alias = cur.fetchall() # Get all parent category list parent_list = list(map(lambda i: (i['term_id'], i['name']), db_terms)) parent_list.insert(0, [0, 'None']) # Populate (id, name) form fields form.parent.choices = parent_list # Get all name list alias_list = list(map(lambda i: i['alias'], db_terms_alias)) # Add category if request.method == 'POST' and form.validate(): name = form.name.data alias = form.alias.data description = form.description.data parent = request.form['parent'] date_update = datetime.now().strftime('%Y-%m-%d %H:%M:%S') if name.lower() not in alias_list: if alias not in alias_list: # Create Cursor cur = mysql.connection.cursor() # Insert user info cur.execute( "INSERT INTO terms(name, alias, description, term_parent, date_update) VALUES(%s, %s, %s, %s, %s)", (name, name.lower() if alias == '' else alias, description, parent, date_update)) # Commit to DB mysql.connection.commit() flash('Category created.', 'success') # Close connection cur.close() return redirect(url_for('.admin_category')) else: flash("'%s' exists, please try another one." % alias, 'warning') return redirect(url_for('.admin_category')) else: # error = 'Category "%s" exists, please try another one.' % name # return render_template("admin/admin_category.html", form=form, error=error) flash("'%s' exists, please try another one." % name, 'warning') return redirect(url_for('.admin_category')) else: # List category # Create cursor cur = mysql.connection.cursor() # Get posts res1 = cur.execute( "SELECT t1.term_id, t1.name, t1.alias, t1.description, t1.date_update, t2.name AS parent FROM terms t1 LEFT JOIN terms t2 ON t1.term_parent = t2.term_id ORDER BY t1.term_id DESC" ) cate = cur.fetchall() # Each page size page_size = 15 # Paginated category list cate_cut = list(paginate(cate, page_size)) # Page number list cate_list = list(range(1, len(cate_cut) + 1)) # Get posts count per each category res2 = cur.execute( "SELECT t.alias, (SELECT Count(p.post_title) FROM posts p WHERE p.post_parent=t.term_id) AS post_count FROM terms t" ) counts = cur.fetchall() # Close connection cur.close() if res1 > 0 and page > 0 and page < len(cate_cut) + 1: return render_template('admin/admin_category.html', cates=cate_cut[page - 1], page=page, page_list=cate_list, form=form, action=action, counts=counts) else: return redirect(url_for('.admin_category'))
def conference_list(request): conferences = Conference.objects.all() context = paginate(conferences, 5, request, {'conferences': conferences}, var_name='conferences') return render(request, 'conference_app/conference_list.html', context)
def admin_invite(page=1): form = InviteForm(request.form) # Create cursor cur = mysql.connection.cursor() # Get invitation res1 = cur.execute("SELECT * FROM invitation order by id desc") db_invite = cur.fetchall() invite_list = list(map(lambda i: i['code'], db_invite)) # Add invitation if request.method == 'POST' and form.validate(): code = form.code.data if code not in invite_list: # Create Cursor cur = mysql.connection.cursor() # Insert user info cur.execute("INSERT INTO invitation(code) VALUES(%s)", (code, )) # Commit to DB mysql.connection.commit() flash('Invitation code created.', 'success') # Close connection cur.close() return redirect(url_for('.admin_invite')) else: flash("'%s' exists, please try another one." % code, 'warning') return redirect(url_for('.admin_invite')) else: # List invitation code # Create cursor cur = mysql.connection.cursor() # Get posts res1 = cur.execute("SELECT id, code FROM invitation") db_invite = cur.fetchall() # Each page size page_size = 10 # Paginated Invitation list inv_cut = list(paginate(db_invite, page_size)) # Page number list inv_list = list(range(1, len(inv_cut) + 1)) # Close connection cur.close() if res1 > 0 and page > 0 and page < len(inv_cut) + 1: return render_template('admin/admin_invite.html', invite=inv_cut[page - 1], page=page, page_list=inv_list, form=form) else: return redirect(url_for('.admin_invite'))
def list(request): paginator, queryset = paginate( request, Location.objects.all(), settings.PHOTOS_PER_PAGE) context = {'paginator': paginator, 'location_list': queryset} return render(request, 'photos/location_list.html', context)