Ejemplo n.º 1
0
    def get(self, request):
        from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
        page = request.GET.get('page', 1)
        username = request.GET.get('username', None)
        versions = None
        lookup_user = None

        # Try to get the versions for the given username
        if not username is None:
            User = get_user_model()
            try:
                lookup_user = User.objects.get(username=username)
                versions = SystemVersion.objects.filter(creator=lookup_user)
            except:
                lookup_user = None
                pass
        if versions is None:
            versions = SystemVersion.objects.all()

        # Sort by timestamps
        versions = versions.order_by('-created')

        paginator = Paginator(versions, 25)
        try:
            versions = paginator.get_page(page)
        except PageNotAnInteger:
            versions = paginator.get_page(1)
        except EmptyPage:
            versions = paginator.get_page(paginator.num_pages)

        return render(request, self.template_name, context={
            'activate': 'recent', # NAV-LINKS
            'versions': versions,
            'lookup_user': lookup_user,
        })
Ejemplo n.º 2
0
 def test_get_page_empty_object_list(self):
     """Paginator.get_page() with an empty object_list."""
     paginator = Paginator([], 2)
     # An empty page returns the last page.
     self.assertEqual(paginator.get_page(1).number, 1)
     self.assertEqual(paginator.get_page(2).number, 1)
     # Non-integer page returns the first page.
     self.assertEqual(paginator.get_page(None).number, 1)
Ejemplo n.º 3
0
 def test_get_page_empty_object_list_and_allow_empty_first_page_false(self):
     """
     Paginator.get_page() raises EmptyPage if allow_empty_first_page=False
     and object_list is empty.
     """
     paginator = Paginator([], 2, allow_empty_first_page=False)
     with self.assertRaises(EmptyPage):
         paginator.get_page(1)
Ejemplo n.º 4
0
 def test_get_page(self):
     """
     Paginator.get_page() returns a valid page even with invalid page
     arguments.
     """
     paginator = Paginator([1, 2, 3], 2)
     page = paginator.get_page(1)
     self.assertEqual(page.number, 1)
     self.assertEqual(page.object_list, [1, 2])
     # An empty page returns the last page.
     self.assertEqual(paginator.get_page(3).number, 2)
     # Non-integer page returns the first page.
     self.assertEqual(paginator.get_page(None).number, 1)
Ejemplo n.º 5
0
    def get(self, request):
        """
        Lists the consultants for the current page, and applies the search
        filter if it exists.
        """

        # search? yes
        try:
            search_term = request.GET.get('search')
            consultants = Consultant.search_consultants(search_term)

        # no
        except KeyError:
            # get all consultants
            consultants = Consultant.search_consultants(None)

        # divide consultants by five per page
        paginator = Paginator(consultants, 5)

        page = request.GET.get('page')
        show_consultants = paginator.get_page(page)

        return render(
            request,
            'consultant/consultants.html', 
            {'consultants': show_consultants}
        )
Ejemplo n.º 6
0
def request_list(request):
    filter = RequestFilter(request.GET, queryset=Request.objects.all() )
    req_data = filter.qs.order_by('-dateadded')
    paginator = Paginator(req_data, 100)
    page = request.GET.get('page')
    req_data = paginator.get_page(page)
    return render(request, 'mainapp/request_list.html', {'filter': filter , "data" : req_data })
Ejemplo n.º 7
0
def warehouse_orders(request):
    vendors, payment_method, currency = Supply.objects.all(), PaymentMethod.objects.all(), CURRENCY
    orders = Order.objects.all()
    orders = Order.filter_data(request, queryset=orders)

    date_start, date_end, date_range, months_list = estimate_date_start_end_and_months(request)
    search_name, vendor_name, balance_name, paid_name = [request.GET.get('search_name'),
                                                         request.GET.getlist('vendor_name'),
                                                         request.GET.get('balance_name'),
                                                         request.GET.get('paid_name')
                                                         ]

    order_count, total_value, paid_value = orders.count(), orders.aggregate(Sum('total_price'))[
        'total_price__sum'] \
        if orders else 0, orders.aggregate(Sum('paid_value'))[
                                               'paid_value__sum'] if orders else 0
    diff = total_value - paid_value
    warehouse_analysis = balance_sheet_chart_analysis(date_start, date_end, orders, 'total_price')
    warehouse_vendors = orders.values('vendor__title').annotate(value_total=Sum('total_price'),
                                                                          paid_val=Sum('paid_value')).order_by(
        '-value_total')
    paginator = Paginator(orders, 100)
    page = request.GET.get('page', 1)
    orders = paginator.get_page(page)
    context = locals()
    return render(request, 'report/orders.html', context)
Ejemplo n.º 8
0
    def get(self, request):

        try:
            search_term = request.GET.get('search')

            # get all results from companies & consultants
            companies = Company.search_companies(search_term)

        except KeyError:
            # get all companies and consultants
            companies = Company.search_companies(None)

        company_filter = CompanyFilter(request.GET, queryset=companies)
        results = company_filter.qs

        paginator = Paginator(results, 8)
        page = request.GET.get('page')
        show_businesses = paginator.get_page(page)

        return render(request, 'companies.html', {
            'company': Member.get_user_company(request.user),
            'show_sidepane': True,
            'companies': show_businesses,
            'page': page,
            'filter': company_filter,
        })
Ejemplo n.º 9
0
    def buildListHTML(self, pageNumber, propertyName, parent):
        modelClass, modelClassName = self.modelClass, self.modelClassName
        modelClassDisplayName = modelClass.getPrettyClassName()
        if propertyName and parent:
            gql = "WHERE %s = :1 ORDER BY %s" % (propertyName, modelClass.NAME_PROPERTY)
            # logging.debug(gql + '(' + parent + ')')
            models = (propertyName and modelClass.gql(gql, db.get(parent))) or modelClass.get()
        else:
            models = modelClass.all()

        paginator = ObjectPaginator(models, 10, orphans=2)
        if paginator.pages < pageNumber:
            pageNumber = paginator.pages
        pageNumber0 = pageNumber - 1
        models = paginator.get_page(pageNumber0)

        firstOnPage, lastOnPage, numModels = (
            paginator.first_on_page(pageNumber0),
            paginator.last_on_page(pageNumber0),
            paginator.hits,
        )
        hasPreviousPage, hasNextPage = paginator.has_previous_page(pageNumber0), paginator.has_next_page(pageNumber0)
        previousPage, nextPage = pageNumber - 1, pageNumber + 1

        listItems = []
        for model in models:
            modelToListItemHTML = lambda model, s=self, p=parent, pn=propertyName: s.modelToListItemHTML(model, p, pn)
            cacheKey = "listItemHTML" + parent
            self.modelClass.setEntityCacheFunctionForKey(modelToListItemHTML, cacheKey)
            listItems.append(model.getEntityCache(cacheKey))
        listItems = "\n".join(listItems)
        return self.renderManagementTemplate(locals(), "List.html")
Ejemplo n.º 10
0
def chooser(request, get_results=False):
    # Get most popular queries
    queries = models.Query.get_most_popular()

    # If searching, filter results by query string
    query_string = None
    if 'q' in request.GET:
        searchform = SearchForm(request.GET)
        if searchform.is_valid():
            query_string = searchform.cleaned_data['q']
            queries = queries.filter(query_string__icontains=normalise_query_string(query_string))
    else:
        searchform = SearchForm()

    paginator = Paginator(queries, per_page=10)
    queries = paginator.get_page(request.GET.get('p'))

    # Render
    if get_results:
        return render(request, "wagtailsearch/queries/chooser/results.html", {
            'queries': queries,
        })
    else:
        return render_modal_workflow(
            request, 'wagtailsearch/queries/chooser/chooser.html', None, {
                'queries': queries,
                'searchform': searchform,
            }, json_data={'step': 'chooser'}
        )
Ejemplo n.º 11
0
    def get_context_data(self, number_of_publications=25, **kwargs):
        context = super(DashboardView, self).get_context_data(**kwargs)
        last_week_datetime = timezone.now() - timedelta(days=14)
        context['status'] = Counter()

        pub_count = Publication.objects.filter(is_primary=True).values('status').annotate(
            total=Count('status')).order_by('-total')
        for item in pub_count:
            total_count = item['total']
            context['status'][item['status']] = total_count
            context['status']['TOTAL'] += total_count
        n_flagged = Publication.objects.filter(is_primary=True, flagged=True).count()
        context['flagged'] = n_flagged

        context['complete'] = Publication.objects.filter(
            is_primary=True, status=Publication.Status.REVIEWED) \
            .annotate(n_code_archive_urls=models.Count('code_archive_urls')) \
            .filter(n_code_archive_urls__gt=0).count()
        context['incomplete'] = context['status'][Publication.Status.REVIEWED] - context['complete']

        context['unreviewed_publications_count'] = Publication.objects.filter(
            status=Publication.Status.UNREVIEWED, assigned_curator=self.request.user).count()
        context['recently_author_updated'] = Publication.objects.filter(
            status=Publication.Status.AUTHOR_UPDATED)
        recently_updated_publications = Publication.objects.exclude(
            status=Publication.Status.AUTHOR_UPDATED)
        recently_updated_list = recently_updated_publications.filter(
            date_modified__gte=last_week_datetime, is_primary=True).order_by('-date_modified')
        paginator = Paginator(recently_updated_list, number_of_publications)
        page = self.request.GET.get('page')
        recently_updated = paginator.get_page(page)
        context['recently_updated'] = recently_updated
        return context
Ejemplo n.º 12
0
Archivo: views.py Proyecto: b2scrip/cms
def user_profile(request):
    posts_list = request.user.post_set.all()
    paginator = Paginator(posts_list, 10) # Show 25 contacts per page
    page = request.GET.get('page')
    posts = paginator.get_page(page)
    context = {"author":request.user,"userposts":posts}
    return render(request,"user/user-profile-posts.html",context)
Ejemplo n.º 13
0
    def __init__(self, searchResults, handler, title, user):
        self.user, self.handler = user, handler
        self.rootNode = rootNode = ElementTree.Element('SearchResults')
        ElementTree.ElementTree.__init__(self, rootNode)

        rootNode.set('title', title)
        rootNode.set('pagelessUrl', self.getPagelessUrlFromHandler(handler))

        # Don't limit the number of results if viewing the characters in a campaign.
        hitsPerPage = handler.request.get('campaign', None) and 100 or self.HITS_PER_PAGE
        paginator = ObjectPaginator(searchResults, hitsPerPage, orphans=self.ORPHANS_PER_PAGE)

        pageNumber = int(handler.request.get('p', '1'))
        numPages = paginator.pages
        pageNumber = min(numPages, pageNumber)
        pageNumber0 = pageNumber - 1

        firstOnPage, lastOnPage, numResults = \
            paginator.first_on_page(pageNumber0), paginator.last_on_page(pageNumber0), paginator.hits
        firstOnPage = lastOnPage and firstOnPage or 0 # so firstOnPage isn't 1 when there are 0 results

        localVars = locals()
        for thisVar in ('numResults', 'numPages', 'pageNumber', 'firstOnPage', 'lastOnPage'):
            rootNode.set(thisVar, str(localVars[thisVar]))

        try:
            [ self.addResult(thisResult, user) for thisResult in paginator.get_page(pageNumber0) ]
        except AttributeError:
            raise
            raise RuntimeError, 'expecting searchResults, got %(searchResults)r' % locals()
Ejemplo n.º 14
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     all_links = self.request.user.links.all()
     paginator = Paginator(all_links, 50)
     page = self.request.GET.get('page')
     context['links'] = paginator.get_page(page)
     return context
Ejemplo n.º 15
0
def move_choose_destination(request, page_to_move_id, viewed_page_id=None):
    page_to_move = get_object_or_404(Page, id=page_to_move_id)
    page_perms = page_to_move.permissions_for_user(request.user)
    if not page_perms.can_move():
        raise PermissionDenied

    if viewed_page_id:
        viewed_page = get_object_or_404(Page, id=viewed_page_id)
    else:
        viewed_page = Page.get_first_root_node()

    viewed_page.can_choose = page_perms.can_move_to(viewed_page)

    child_pages = []
    for target in viewed_page.get_children():
        # can't move the page into itself or its descendants
        target.can_choose = page_perms.can_move_to(target)

        target.can_descend = (
            not(target == page_to_move
                or target.is_child_of(page_to_move))
            and target.get_children_count()
        )

        child_pages.append(target)

    # Pagination
    paginator = Paginator(child_pages, per_page=50)
    child_pages = paginator.get_page(request.GET.get('p'))

    return render(request, 'wagtailadmin/pages/move_choose_destination.html', {
        'page_to_move': page_to_move,
        'viewed_page': viewed_page,
        'child_pages': child_pages,
    })
Ejemplo n.º 16
0
def posts_list(request):
    search_query = request.GET.get('search', '')
    if search_query:
        posts = Post.objects.filter(Q(title__icontains=search_query) | Q(body__icontains=search_query))
    else:
        posts = Post.objects.all()

    paginator = Paginator(posts, posts_on_page)

    page_number = request.GET.get('page', 1)
    page = paginator.get_page(page_number)
    is_paginated = page.has_other_pages()

    if page.has_previous():
        prev_url = '?page={}'.format(page.previous_page_number())
    else:
        prev_url = ''

    if page.has_next():
        next_url = '?page={}'.format(page.next_page_number())
    else:
        next_url = ''

    context = {
        'page_object':page,
        'is_paginated':is_paginated,
        'next_url':next_url,
        'prev_url':prev_url
    }

    return render(request, 'blog/index.html', context=context)
Ejemplo n.º 17
0
def chooser_upload(request):
    Image = get_image_model()
    ImageForm = get_image_form(Image)

    if request.method == 'POST':
        image = Image(uploaded_by_user=request.user)
        form = ImageForm(
            request.POST, request.FILES, instance=image, user=request.user, prefix='image-chooser-upload'
        )

        if form.is_valid():
            # Set image file size
            image.file_size = image.file.size

            # Set image file hash
            image.file.seek(0)
            image._set_file_hash(image.file.read())
            image.file.seek(0)

            form.save()

            # Reindex the image to make sure all tags are indexed
            search_index.insert_or_update_object(image)

            if request.GET.get('select_format'):
                form = ImageInsertionForm(
                    initial={'alt_text': image.default_alt_text}, prefix='image-chooser-insertion'
                )
                return render_modal_workflow(
                    request, 'wagtailimages/chooser/select_format.html', None,
                    {'image': image, 'form': form}, json_data={'step': 'select_format'}
                )
            else:
                # not specifying a format; return the image details now
                return render_modal_workflow(
                    request, None, None,
                    None, json_data={'step': 'image_chosen', 'result': get_image_result_data(image)}
                )
    else:
        form = ImageForm(user=request.user, prefix='image-chooser-upload')

    images = Image.objects.order_by('-created_at')

    # allow hooks to modify the queryset
    for hook in hooks.get_hooks('construct_image_chooser_queryset'):
        images = hook(images, request)

    paginator = Paginator(images, per_page=12)
    images = paginator.get_page(request.GET.get('p'))

    context = get_chooser_context(request)
    context.update({
        'images': images,
        'uploadform': form,
    })
    return render_modal_workflow(
        request, 'wagtailimages/chooser/chooser.html', None, context,
        json_data=get_chooser_js_data()
    )
Ejemplo n.º 18
0
def index(request):
    Image = get_image_model()

    # Get images (filtered by user permission)
    images = permission_policy.instances_user_has_any_permission_for(
        request.user, ['change', 'delete']
    ).order_by('-created_at')

    # Search
    query_string = None
    if 'q' in request.GET:
        form = SearchForm(request.GET, placeholder=_("Search images"))
        if form.is_valid():
            query_string = form.cleaned_data['q']

            images = images.search(query_string)
    else:
        form = SearchForm(placeholder=_("Search images"))

    # Filter by collection
    current_collection = None
    collection_id = request.GET.get('collection_id')
    if collection_id:
        try:
            current_collection = Collection.objects.get(id=collection_id)
            images = images.filter(collection=current_collection)
        except (ValueError, Collection.DoesNotExist):
            pass

    paginator = Paginator(images, per_page=20)
    images = paginator.get_page(request.GET.get('p'))

    collections = permission_policy.collections_user_has_any_permission_for(
        request.user, ['add', 'change']
    )
    if len(collections) < 2:
        collections = None
    else:
        collections = Collection.order_for_display(collections)

    # Create response
    if request.is_ajax():
        return render(request, 'wagtailimages/images/results.html', {
            'images': images,
            'query_string': query_string,
            'is_searching': bool(query_string),
        })
    else:
        return render(request, 'wagtailimages/images/index.html', {
            'images': images,
            'query_string': query_string,
            'is_searching': bool(query_string),

            'search_form': form,
            'popular_tags': popular_tags_for_model(Image),
            'collections': collections,
            'current_collection': current_collection,
            'user_can_add': permission_policy.user_has_permission(request.user, 'add'),
        })
Ejemplo n.º 19
0
Archivo: views.py Proyecto: b2scrip/cms
def user_posts_detail(request,id):
    author = get_object_or_404(User,pk=id)
    posts_list = author.post_set.all()
    paginator = Paginator(posts_list, 25) # Show 25 contacts per page
    page = request.GET.get('page')
    posts = paginator.get_page(page)
    context = {"author":author,"userposts":posts}
    return render(request,"user/user-posts-all.html",context)
Ejemplo n.º 20
0
Archivo: views.py Proyecto: b2scrip/cms
def user_posts_gallery(request,id):
    author = get_object_or_404(User,pk=id)
    gallery_list = author.picture_set.all()
    paginator = Paginator(gallery_list, 15) # Show 25 contacts per page
    page = request.GET.get('page')
    gallerys = paginator.get_page(page)
    context = {"author":author,"gallerys":gallerys}
    return render(request,"user/user-posts-gallery.html",context)
Ejemplo n.º 21
0
 def getModelPageNumber(self, model):
     modelKey = model.key()
     allModels = self.modelClass.get()
     paginator = ObjectPaginator(allModels, 10, orphans=2)
     for pageNumber in range(paginator.pages):
         for thisModel in paginator.get_page(pageNumber):
             if thisModel.key() == modelKey:
                 return pageNumber
Ejemplo n.º 22
0
 def _paged_offers(page_queryset, page_num, page_size):
     if page_num <= 0:
         return []
     paged_products = Paginator(page_queryset, page_size)
     if page_num > paged_products.num_pages:
         return []
     page = paged_products.get_page(page_num)
     return page.object_list
Ejemplo n.º 23
0
def list(request, app_label, model_name):
    model = get_snippet_model_from_url_params(app_label, model_name)

    permissions = [
        get_permission_name(action, model)
        for action in ['add', 'change', 'delete']
    ]
    if not any([request.user.has_perm(perm) for perm in permissions]):
        return permission_denied(request)

    items = model.objects.all()

    # Preserve the snippet's model-level ordering if specified, but fall back on PK if not
    # (to ensure pagination is consistent)
    if not items.ordered:
        items = items.order_by('pk')

    # Search
    is_searchable = class_is_indexed(model)
    is_searching = False
    search_query = None
    if is_searchable and 'q' in request.GET:
        search_form = SearchForm(request.GET, placeholder=_("Search %(snippet_type_name)s") % {
            'snippet_type_name': model._meta.verbose_name_plural
        })

        if search_form.is_valid():
            search_query = search_form.cleaned_data['q']

            search_backend = get_search_backend()
            items = search_backend.search(search_query, items)
            is_searching = True

    else:
        search_form = SearchForm(placeholder=_("Search %(snippet_type_name)s") % {
            'snippet_type_name': model._meta.verbose_name_plural
        })

    paginator = Paginator(items, per_page=20)
    paginated_items = paginator.get_page(request.GET.get('p'))

    # Template
    if request.is_ajax():
        template = 'wagtailsnippets/snippets/results.html'
    else:
        template = 'wagtailsnippets/snippets/type_index.html'

    return render(request, template, {
        'model_opts': model._meta,
        'items': paginated_items,
        'can_add_snippet': request.user.has_perm(get_permission_name('add', model)),
        'can_delete_snippets': request.user.has_perm(get_permission_name('delete', model)),
        'is_searchable': is_searchable,
        'search_form': search_form,
        'is_searching': is_searching,
        'query_string': search_query,
    })
Ejemplo n.º 24
0
def choose(request, app_label, model_name):
    model = get_snippet_model_from_url_params(app_label, model_name)

    items = model.objects.all()

    # Preserve the snippet's model-level ordering if specified, but fall back on PK if not
    # (to ensure pagination is consistent)
    if not items.ordered:
        items = items.order_by('pk')

    # Search
    is_searchable = class_is_indexed(model)
    is_searching = False
    search_query = None
    if is_searchable and 'q' in request.GET:
        search_form = SearchForm(request.GET, placeholder=_("Search %(snippet_type_name)s") % {
            'snippet_type_name': model._meta.verbose_name
        })

        if search_form.is_valid():
            search_query = search_form.cleaned_data['q']

            search_backend = get_search_backend()
            items = search_backend.search(search_query, items)
            is_searching = True

    else:
        search_form = SearchForm(placeholder=_("Search %(snippet_type_name)s") % {
            'snippet_type_name': model._meta.verbose_name
        })

    # Pagination
    paginator = Paginator(items, per_page=25)
    paginated_items = paginator.get_page(request.GET.get('p'))

    # If paginating or searching, render "results.html"
    if request.GET.get('results', None) == 'true':
        return render(request, "wagtailsnippets/chooser/results.html", {
            'model_opts': model._meta,
            'items': paginated_items,
            'query_string': search_query,
            'is_searching': is_searching,
        })

    return render_modal_workflow(
        request,
        'wagtailsnippets/chooser/choose.html', None,
        {
            'model_opts': model._meta,
            'items': paginated_items,
            'is_searchable': is_searchable,
            'search_form': search_form,
            'query_string': search_query,
            'is_searching': is_searching,
        }, json_data={'step': 'choose'}
    )
Ejemplo n.º 25
0
def forum_list(request):
    all_questions = Question.objects.all()
    paginator = Paginator(all_questions, 5)  # Show 5 contacts per page

    page = request.GET.get('page')
    questions = paginator.get_page(page)
    if request.method == 'GET':
        question_form = QuestionModelForm()

    return render(request, 'dashboard/list_ajax.html', {'questions': questions, 'question_form': question_form})
Ejemplo n.º 26
0
def usage(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

    paginator = Paginator(image.get_usage(), per_page=20)
    used_by = paginator.get_page(request.GET.get('p'))

    return render(request, "wagtailimages/images/usage.html", {
        'image': image,
        'used_by': used_by
    })
Ejemplo n.º 27
0
def usage(request, document_id):
    Document = get_document_model()
    doc = get_object_or_404(Document, id=document_id)

    paginator = Paginator(doc.get_usage(), per_page=20)
    used_by = paginator.get_page(request.GET.get('p'))

    return render(request, "wagtaildocs/documents/usage.html", {
        'document': doc,
        'used_by': used_by
    })
Ejemplo n.º 28
0
def usage(request, app_label, model_name, pk):
    model = get_snippet_model_from_url_params(app_label, model_name)
    instance = get_object_or_404(model, pk=unquote(pk))

    paginator = Paginator(instance.get_usage(), per_page=20)
    used_by = paginator.get_page(request.GET.get('p'))

    return render(request, "wagtailsnippets/snippets/usage.html", {
        'instance': instance,
        'used_by': used_by
    })
Ejemplo n.º 29
0
def front_page(request):
    jobs = Job.objects.all().filter(filled=False).filter(approved=True).order_by("-id")
    paginator = Paginator(jobs, 15)
    page = request.GET.get("page")
    return render(
        request,
        "main_page.html",
        {
            "jobs": paginator.get_page(page)
        }
    )
Ejemplo n.º 30
0
def new_dashboard(request):
    statistics = Statistics(request.user) # type: Statistics
    goals = Goals(request.user)

    paginator = Paginator(Workout.objects.filter(user=request.user), 20)
    page = request.GET.get("page")
    workouts = paginator.get_page(page)

    return render(request, 'training/new_dashboard.html', {'statistics': statistics,
                                                       'goals': goals,
                                                       'days_left_in_this_month': dates.days_left_in_this_month(),
                                                       'workouts': workouts})
Ejemplo n.º 31
0
def transactions(request):
    dvds = DVD.objects.all()  #imports dvds from database
    trans = Transaction.objects.all()  #imports dvds from database
    users = User.objects.all()  #imports dvds from database
    customer = Customer.objects.all()  #imports dvds from database

    query = request.GET.get("query")
    if query:
        trans = Transaction.objects.filter(
            Q(TransactionNumber__icontains=query)
        )  #Search Function according to name

    paginator = Paginator(dvds, 6)  # Show 3 dvds per page
    page = request.GET.get('page')
    dvds = paginator.get_page(page)
    form = DocumentForm()
    context_dict = {
        'dvds': dvds,
        'form': form,
        'trans': trans,
        'users': users,
        'customer': customer
    }
    return render(request, 'transactions.html', context_dict)
Ejemplo n.º 32
0
def index(request):
    if request.method == 'POST':
        #salva os dados e a foto
        product_form = ProductForm(data=request.POST,files=request.FILES,)
        # Verifica se o formulario é valido
        if product_form.is_valid(): 
            # Salva o produto
            product_form.save()
            # Confirma com mensagem na tela
            messages.success(request, 'Produto Salvo com Sucesso')
            #Vai para pagina principal
            return HttpResponseRedirect(reverse('index'))
        else:
            # Avisa o motivo do erro no shell.
            print(product_form.errors)

    else:
        # Renderiza um formulario para cadastro .
        product_form = ProductForm()

    # Cria uma lista por ordem decrescente por data
    product_list = Product.objects.all().order_by('-date') 
 
    #Paginação
    page_number = request.GET.get('page') 
    paginator = Paginator(product_list,3) # Mostra nemero de itens por pagina, no caso 3.
    try:
        pages = paginator.page(page_number)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.get_page(page_number)
    

    context = { 'product_form': product_form, 'pages':pages }
    return render(request, 'base/index.html' , context) 
Ejemplo n.º 33
0
    def get(self, request):
        model = CommentsModel.objects.order_by('-timedate')
        paginator = Paginator(model, 3)
        page_number = request.GET.get('page', 1)
        page = paginator.get_page(page_number)

        is_paginated = page.has_other_pages()

        if page.has_previous():
            prev_url = '?page={}'.format(page.previous_page_number())
        else:
            prev_url = ''

        if page.has_next():
            next_url = '?page={}'.format(page.next_page_number())
        else:
            next_url = ''

        if request.user.is_authenticated:
            initial = {
                'surname': request.user.first_name,
                'name': request.user.last_name,
            }
            form = CommentsForm(initial=initial)
        else:
            form = CommentsForm()

        context = {
            'form': form,
            'model': page,
            'prev_url': prev_url,
            'next_url': next_url,
            'is_paginated': is_paginated,
        }

        return render(request, 'comments/comments.html', context=context)
Ejemplo n.º 34
0
def index(request, sort=None):

    if sort == 'rank':
        movies = Movie.objects.order_by('-vote_average').filter(
            release_date__lte=datetime.datetime.now())
    elif sort == 'release':
        movies = Movie.objects.order_by('-release_date').filter(
            release_date__lte=datetime.datetime.now())
    else:
        movies = Movie.objects.order_by('-pk').filter(
            release_date__lte=datetime.datetime.now())
    paginator = Paginator(movies, 12)
    nowDate = datetime.datetime.now().strftime('%Y-%m-%d')
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    context = {
        'page_obj': page_obj,
        'nowDate': nowDate,
    }

    if not page_number or int(page_number) == 1:
        return render(request, 'movies/index.html', context)
    else:
        return render(request, 'movies/index_scroll.html', context)
Ejemplo n.º 35
0
def profile(request, username):
    username = get_object_or_404(User, username=username)
    tag = request.GET.getlist('filters')
    recipes = Recipe.objects.filter(author=username).\
        select_related('author').all()
    if tag:
        recipes = recipes.filter(tags__slug__in=tag)
    paginator = Paginator(recipes, 6)
    page_number = request.GET.get('page')
    page = paginator.get_page(page_number)

    if request.user.is_authenticated:
        following = FollowUser.objects.filter(user=request.user).\
            filter(author=username).select_related('author')
        if not following:
            following = None
        else:
            following = True
        return render(request, "authorRecipe.html",
                      {'username': username, 'page': page,
                       'paginator': paginator, 'following': following})
    return render(request, "authorRecipe.html",
                  {'username': username, 'page': page,
                   'paginator': paginator, })
Ejemplo n.º 36
0
def search(request):
    show_tags = False
    search_string = request.GET.get('search')
    page = request.GET.get('page')
    param_search = search_string
    try:
        items = Item.objects.filter(name_lower__contains=search_string.lower(),
                                    is_active=True)
    except:
        return render(request, '404.html', locals())
    if not items:
        items = Item.objects.filter(
            name_lower__contains=search_string.lower()[:-1], is_active=True)
    if not items:
        items = Item.objects.filter(article__contains=search_string)
    items_paginator = Paginator(items, 12)
    try:
        items = items_paginator.get_page(page)
    except PageNotAnInteger:
        items = items_paginator.page(1)
    except EmptyPage:
        items = items_paginator.page(items_paginator.num_pages)

    return render(request, 'page/search.html', locals())
Ejemplo n.º 37
0
def user_profile(request, username):
    user = get_object_or_404(User, username=username)

    if request.user.username != username:
        post_list = Blog.objects.filter(
            user=user, published=True,
            created_at__lte=timezone.now()).order_by('-created_at')
        is_self = False
    else:
        post_list = Blog.objects.filter(
            user=user, created_at__lte=timezone.now()).order_by('-created_at')
        is_self = True

    paginator = Paginator(post_list, 3)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    return render(request,
                  "Blog/user_profile.html",
                  context={
                      "author": user,
                      "page_obj": page_obj,
                      "is_self": is_self
                  })
Ejemplo n.º 38
0
def index(request):
    postsdata = Post.objects.all().order_by('-timestamp')
    loggedUser = ''
    if (request.user.is_authenticated):
        loggedUser = User.objects.get(username=request.user.username)

    p = Paginator(postsdata, 10)

    pagenumber = request.GET.get('page')

    if pagenumber == None:
        pagenumber = 1
    elif int(pagenumber) > int(p.num_pages):
        pagenumber = 1
    else:
        pagenumber = int(pagenumber)

    maindata = p.get_page(pagenumber)

    return render(request, "network/index.html", {
        'data': maindata,
        'loggedUser': loggedUser,
        'page_obj': maindata,
    })
Ejemplo n.º 39
0
def index(request):
    # return HttpResponse('Hello There~')
    issues = Issue.objects.order_by('-pub_at')
    paginator = Paginator(issues, 6)  # 实例化paginator,每页X条数据
    page_number = request.GET.get('page')  # 获取当前页码
    page_obj = paginator.get_page(page_number)  # 根据当前页码获取实例对象

    # 这部分是为了再有大量数据时,仍然保证所显示的页码数量不超过10,
    page_num = request.GET.get('page', default='1')
    page_num = int(page_num)
    if page_num < 6:
        if paginator.num_pages <= 10:
            dis_range = range(1, paginator.num_pages + 1)
        else:
            dis_range = range(1, 11)
    elif (page_num >= 6) and (page_num <= paginator.num_pages - 5):
        dis_range = range(page_num - 5, page_num + 5)
    else:
        dis_range = range(paginator.num_pages - 9, paginator.num_pages + 1)

    return render(request, 'issues/index.html', {
        'page_obj': page_obj,
        'dis_range ': dis_range
    })
Ejemplo n.º 40
0
def index(request):
    if 'search_filter' in request.GET:
        search_filter = request.GET['search_filter']
        consoles = [{
            'id':
            x.id,
            'name':
            x.console_name,
            'description':
            x.console_short_description,
            'firstImage':
            x.consoleimage_set.first().console_image_image
        } for x in Console.objects.filter(
            console_name__icontains=search_filter)]

        return JsonResponse({'data': consoles})

    consoles = Console.objects.all().order_by('console_name')
    paginator = Paginator(consoles, 6)
    page = request.GET.get('page')
    paged_consoles = paginator.get_page(page)
    context = {'console': paged_consoles}

    return render(request, 'consoles/index.html', context=context)
Ejemplo n.º 41
0
def search(request):
    query = request.GET.get('q')

    if not query:
        return redirect("home-page")

    requests = None
    time_deltas = []
    if query:
        requests = FeedbackRequestDocument.search().query(
            "multi_match", query=query, fields=['title', 'maintext'])
        requests = requests.to_queryset()
        requests = requests.filter(feedbackee=F('feedbacker')).exclude(
            feedbackee=request.user)
        page_number = request.GET.get('page', 1)  # defaults to 1 if not found
        paginator = Paginator(requests,
                              5)  # each page contains 5 feedback requests
        requests = paginator.get_page(page_number)
        page_obj = requests

        curr_time = datetime.now(timezone.utc)
        for feedback_request in requests:
            time_posted = feedback_request.date_posted
            time_deltas.append(get_time_delta(time_posted, curr_time))
    else:
        page_obj = None
    context = {
        'requests': requests,
        'search': query,
        'areas': Area.objects.all(),
        'page_obj': page_obj,
        'time_deltas': time_deltas,
        'title': '| Search'
    }

    return render(request, 'main/search-requests.html', context)
Ejemplo n.º 42
0
def products(request):
    """
    View for showing all ads that are not sold, ordering them by date created
    and paginating them over multiple pages

    :param request: A django HttpRequest object. The session of the user.
    :return:
        render: A render with the product_listEXT.html file
    """
    products = Advertisement.objects.all().filter(
        sold=False).order_by('-created_date')
    paginator = Paginator(products, 6)  # Show X products per page

    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    categories = Category.objects.all()

    context = {
        'products': page_obj.object_list,
        'page_obj': page_obj,
        'categories': categories
    }

    return render(request, 'sellyoshit/product_listEXT.html', context)
Ejemplo n.º 43
0
def by_rubric(request, pk):
    """ вывод объявлений """
    rubric = get_object_or_404(SubRubric, pk=pk)
    bbs = Bb.objects.filter(is_active=True, rubric=pk)
    if 'keyword' in request.GET:
        keyword = request.GET['keyword']
        q = Q(title__icontains=keyword) | Q(content__icontains=keyword)
        bbs = bbs.filter(q)
    else:
        keyword = ''
    form = SearchForm(initial={'keyword': keyword})
    paginator = Paginator(bbs, 2)
    if 'page' in request.GET:
        page_num = request.GET['page']
    else:
        page_num = 1
    page = paginator.get_page(page_num)
    context = {
        'rubric': rubric,
        'page': page,
        'bbs': page.object_list,
        'form': form
    }
    return render(request, 'main/by_rubric.html', context)
Ejemplo n.º 44
0
def result_table(request):

    check = False

    result = Result.objects.all().order_by('-id')

    paginator = Paginator(result, 1)  # Show 10 obj per page

    page = request.GET.get('page')
    result = paginator.get_page(page)

    if request.method == 'POST' and 'btn-search' in request.POST:
        q = request.POST.get('search').strip()
        result = Result.objects.filter(Q(studentId__icontains = q)).order_by('-id')
        check = True 
    
    context = {
        'result': result,
        'check' : check,
    }



    return render(request, 'result/result_table.html', context)
Ejemplo n.º 45
0
def generate_result_from_paginator_for_admin_portal(model_cls,
                                                    serializer_cls,
                                                    search_options=None,
                                                    sort_options=(),
                                                    page_number=1,
                                                    page_size=20):
    qs = model_cls.objects.order_by('-id')

    if sort_options:
        for option in sort_options:
            qs = qs.order_by(option)

    if search_options:
        qs = qs.filter(**search_options)

    paginator = Paginator(qs, page_size, allow_empty_first_page=True)
    page = paginator.get_page(page_number)

    data = serializer_cls(instance=page.object_list, many=True).data

    return {
        'data': data,
        'total': paginator.count,
    }
Ejemplo n.º 46
0
def my_page(request):
    """
    Renders a page displaying the logged in user's ads

    :param request: A django HttpRequest object. The session of the user.
    :return:
        redirect: Redirects to home if the user if not logged in
        render: Renders the logged in user's ad in the file mypage.html
    """
    user = request.user
    if not user.is_authenticated:
        return redirect('home')
    products = Advertisement.objects.all().filter(seller=user.userid)
    paginator = Paginator(products, 6)  # Show X products per page

    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {'products': page_obj.object_list,
               'page_obj': page_obj,
               'categories': Category.objects.all()
               }

    return render(request, 'sellyoshit/mypage.html', context)
Ejemplo n.º 47
0
def index(request):
    """
    pybo 목록 출력
    """

    # 입력 파라미터
    page = request.GET.get('page', '1')  # 페이지
    kw = request.GET.get('kw', '')  # 검색어
    so = request.GET.get('so', 'recent')

    # 정렬
    if so == 'recommend':
        question_list = Question.objects.annotate(
            num_voter=Count('voter')).order_by('-num_voter', '-create_date')
    elif so == 'popular':
        question_list = Question.objects.annotate(
            num_answer=Count('answer')).order_by('-num_answer', '-create_date')
    else:
        question_list = Question.objects.order_by('-create_date')

    # 검색
    if kw:
        question_list = question_list.filter(
            Q(subject__icontains=kw) |  # 제목검색
            Q(content__icontains=kw) |  # 내용검색
            Q(author__username__icontains=kw) |  #질문 글쓴이검색
            Q(answer__author__username__icontains=kw)  # 답변 글쓴이검색
        ).distinct()

    # 페이징처리
    paginator = Paginator(question_list, 10)  #  페이지당 10개씩 보여주기
    page_obj = paginator.get_page(page)

    context = {'question_list': page_obj, 'page': page, 'kw': kw, 'so': so}

    return render(request, 'pybo/question_list.html', context)
Ejemplo n.º 48
0
def blog_get_paginator(request, blogs_all_list):
    context = {}
    paginator = Paginator(blogs_all_list, 5)
    page_num = request.GET.get('page', 1)
    page_of_blogs = paginator.get_page(page_num)
    curentr_page_num = page_of_blogs.number
    page_range = list(range(max(curentr_page_num-2, 1), curentr_page_num)) + \
                 list(range(curentr_page_num, min(curentr_page_num + 2, paginator.num_pages) + 1))
    if page_range[0] - 1 >= 2:
        page_range.insert(0, '...')
    if paginator.num_pages - page_range[-1] >= 2:
        page_range.append('...')
    if page_range[0] != 1:
        page_range.insert(0, 1)
    if page_range[-1] != paginator.num_pages:
        page_range.append(paginator.num_pages)
    blog_dates = Blog.objects.dates("create_time", "month", order="DESC")
    blog_types = BlogType.objects.all()
    blog_type_list = []
    for blog_type in blog_types:
        blog_type.blog_count = Blog.objects.filter(blog_type=blog_type, is_delete=False).count()
        blog_type_list.append(blog_type)
    blog_date_list = {}
    for blog_date in blog_dates:
        blog_count = Blog.objects.filter(create_time__year=blog_date.year,
                                         create_time__month = blog_date.month, is_delete=False).count()
        blog_date_list[blog_date] = blog_count   
        print(blog_date.month)
    #缓存数据
    
    context["page_of_blogs"] = page_of_blogs
    context["blog_types"] = blog_types
    context["blogs"] = page_of_blogs.object_list
    context["page_range"] = page_range
    context["blog_dates"] = blog_date_list
    return context
Ejemplo n.º 49
0
def user_visit_list(request):
    # Medical Center
    med_center = MedicalCenter.objects.all()[:1].get()

    # Get doctor first
    user_id = request.user.id
    user = User.objects.get(id=user_id)
    # Visits
    visits = []
    if user.role == 0:
        visits = Visit.objects.filter(doctor__profile_id=user_id)
    elif user.role == 1:
        visits = Visit.objects.filter(
            patient__profile_id=user_id).order_by('-start_time')
    paginator = Paginator(visits, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    context = {"page_obj": page_obj, "med_center": med_center}
    if user.role == 0:
        return render(request, "visit/visits-list.html", context=context)
    elif user.role == 1:
        return render(request,
                      "visit/patient-visit-list.html",
                      context=context)
Ejemplo n.º 50
0
    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
        """
        pybo 목록 출력
        """
        logger.info("pybo 목록을 출력합니다.")
        # 입력 파라미터
        page = request.GET.get('page', '1')  # 페이지
        kw = request.GET.get('kw', '')  # 검색어
        so = request.GET.get('so', 'recent')  # 정렬기준

        # 정렬
        if so == 'recommend':
            question_list = Question.objects.annotate(
                num_voter=Count('voter')).order_by('-num_voter', '-created_on')
        elif so == 'popular':
            question_list = Question.objects.annotate(
                num_answer=Count('answer')).order_by('-num_answer', '-created_on')
        else:  # recent
            question_list = Question.objects.order_by('-created_on')

        # 검색
        if kw:
            question_list = question_list.filter(
                Q(subject__icontains=kw) |  # 제목검색
                Q(content__icontains=kw) |  # 내용검색
                Q(created_by__username__icontains=kw) |  # 질문 글쓴이검색
                Q(answer__created_by__username__icontains=kw)  # 답변 글쓴이검색
            ).distinct()

        # 페이징처리
        paginator = Paginator(question_list, 10)  # 페이지당 10개씩 보여주기
        page_obj = paginator.get_page(page)

        context = {'question_list': page_obj, 'page': page,
                   'kw': kw, 'so': so}  # <------ so 추가
        return self.render_to_response(context)
Ejemplo n.º 51
0
def listwithrawquerywithpaginator(request):
    data = request.GET.copy()
    # data = dict()
    # connection.row_factory = sqlite3.Row
    # cursor = connection.cursor()
    with sqlite3.connect("db.sqlite3") as con:
        con.row_factory = sqlite3.Row
        cur = con.cursor()
        cur.execute("select * from economic")
        contact_list = cur.fetchall()

    paginator = Paginator(contact_list, 5)  # Show 15 contacts per page.

    page_number = request.GET.get('page')
    page_number = page_number if page_number else 1
    data['page_obj'] = paginator.get_page(page_number)

    page_obj = data['page_obj']
    for row in page_obj:
        print(f"{row['title']}, {row['link']}")

    return render(request,
                  'board/listwithrawquerywithpaginator.html',
                  context=data)
Ejemplo n.º 52
0
def details(request, slug, title):
    keyword = request.GET.get("keyword")
    if keyword:
        articles = Article.objects.filter(title__contains=keyword)
        paginator = Paginator(articles, 10)
        page = request.GET.get('page')
        contacts = paginator.get_page(page)
        return render(request, "articles.html", {
            "contacts": contacts,
            "keyword": keyword
        })
    list = (Category.objects.all())
    for i in list:
        k = i.slug
        if slug == str(k):
            article = get_object_or_404(Article, seo=title, category=i)
            comments = article.comments.all()
            context = {"article": article, "comments": comments}
            article.views = article.views + 1
            article.save()
            return render(request, "detail.html", context)
    article.views = article.views + 1
    article.save()
    return render(request, "detail.html", context)
Ejemplo n.º 53
0
def index(request):
    given_types = get_filter_type(request)
    no_chosen_types = False
    if given_types is None:
        recipe_list = Recipe.objects.all()
    else:
        types = RecipeType.objects.filter(id__in=given_types)
        if not types:
            no_chosen_types = True
        recipe_list = Recipe.objects.get_index_in_types(types)
    url_type_line = get_url_with_types(request)
    all_types = RecipeType.objects.all()
    paginator = Paginator(recipe_list, OBJECT_PER_PAGE)
    page_number = request.GET.get('page')
    page = paginator.get_page(page_number)
    data = {
        'paginator': paginator,
        'page': page,
        'types': all_types,
        'given_types': given_types,
        'url_type_line': url_type_line,
        'no_chosen_types': no_chosen_types
    }
    return render(request, 'index.html', data)
Ejemplo n.º 54
0
    def get(self, request, pk):
        if not User.objects.filter(id=pk):
            page_title = "Пользователь не найден"
            message = 'Пользователь не найден'
            return render(request, 'mathhack/errors/Not_founded_user.html',
                          {'page_title': page_title, 'message': message, }, )
        else:
            this_user = User.objects.get(id=pk)
            page_title = str(this_user.username)

            statistics = this_user.customer.solved_variants.all()[::-1]
            paginator = Paginator(statistics, 10)

            page_number = request.GET.get('page')
            page_obj = paginator.get_page(page_number)

            if this_user.customer.points_num != 0:
                average_point = this_user.customer.points_sum / this_user.customer.points_num
                average_point = '{0:0.2f}'.format(average_point)
            else:
                average_point = 'No information'
            return render(request, 'mathhack/auth/user_page.html',
                          {'this_user': this_user, 'page_title': page_title, 'pk': pk, 'average_point': average_point,
                           'statistics': statistics, 'page_obj': page_obj})
Ejemplo n.º 55
0
def badge_view(request, uid):
    badge = Badge.objects.filter(uid=uid).annotate(
        count=Count("award")).first()
    target = request.GET.get('user')
    page = request.GET.get('page', 1)

    user = User.objects.filter(profile__uid=target).first()

    if not badge:
        messages.error(request, f"Badge with id={uid} does not exist.")
        return redirect(reverse("badge_list"))

    awards = badge.award_set.all().order_by("-date")
    if user:
        awards = awards.filter(user=user)

    awards = awards.prefetch_related("user", "user__profile", "post",
                                     "post__root")
    paginator = Paginator(object_list=awards, per_page=settings.POSTS_PER_PAGE)

    awards = paginator.get_page(page)
    context = dict(awards=awards, badge=badge)

    return render(request, "badge_view.html", context=context)
Ejemplo n.º 56
0
def news_list(request):

    news_lists = News.objects.all()
    paginator = Paginator(news_lists, 3) 
    page_num = request.GET.get('page', 1) 
    page_of_news = paginator.get_page(page_num) 
    current_page_num = page_of_news.number 
    page_range = list(range(max(1, current_page_num - 2), current_page_num)) + \
                 list(range(current_page_num, min(paginator.num_pages, current_page_num + 2) + 1))

    if page_range[0] -1 >= 2:
        page_range.insert(0, '...')
    if page_range[-1] + 2 <= paginator.num_pages:
        page_range.append('...') 
    #加上首頁與尾頁
    if page_range[0] != 1: 
        page_range.insert(0, 1)
    if page_range[-1] != paginator.num_pages:
        page_range.append(paginator.num_pages)
    context={}
    context['news_lists'] = page_of_news.object_list
    context['page_of_news'] = page_of_news
    context['page_range'] = page_range 
    return render(request, 'news_list.html',context)
Ejemplo n.º 57
0
def delete_before_match_info(request,match_pk) :
	try :
		pk=request.session.get('pk')
		player_name = request.GET.get('player_name')
		
		if pk is None :
			return redirect('/')

		match=Match.objects.get(pk=match_pk)
		match.delete()
		matches = Match.objects.all().filter(accept=False).order_by('-pk')
		count = matches.count()
		paginator = Paginator(matches, 10)
		pages = request.GET.get('page',1)
		matches = paginator.get_page(pages)
	except PageNotAnInteger :
		matches = paginator.page(1)
	except EmptyPage :
		matches = paginator.page(paginator.num_pages)
		return HttpResponse("end")
	except Exception as e :
		return HttpResponse("게시물이 존재하지 않습니다.")

	return render(request, 'hzm/match_before.html',{'matches' : matches, 'count':count, 'pk':pk, 'player_name':player_name})
Ejemplo n.º 58
0
def get_all_common_data(request, articles_all_list):
    paginator = Paginator(articles_all_list,
                          settings.ARTICLE_NUMBER_EACH_PAGE)  # 8篇一页
    # 获取页码参数(GET请求)  .GET 字典 使用get方法判断是否有page值,没有返回1
    page_num = request.GET.get("page", 1)
    # 输入许可字符范围外的字符会返回1
    page_of_articles = paginator.get_page(page_num)

    # 获取当前页
    current_page = page_of_articles.number
    # 页码显示范围
    page_range = [
        i for i in range(current_page - 2, current_page + 3)
        if 0 < i <= paginator.num_pages
    ]
    # 第一页
    if page_range[0] >= 2:
        page_range.insert(0, 1)  # 第一位插入1页码
        if page_range[1] != 2:
            page_range.insert(1, '...')  # 加上...
    # 最后一页
    if page_range[-1] <= paginator.num_pages - 1:
        if page_range[-1] != paginator.num_pages - 1:
            page_range.append('...')  # 加上...
        page_range.append(paginator.num_pages)

    context = {}
    # context['articles'] = page_of_articles.object_list  #   前端页面
    context['page_of_articles'] = page_of_articles  # 当前页码
    # context['article_types'] = artcile_types_list  # 所有分类
    context['article_types'] = ArticleType.objects.annotate(
        article_count=Count('art_art'))  # 所有分类
    # context['article_dates'] = Articles.objects.dates('created_time', 'month', order='DESC')
    context['article_dates'] = get_categories_count()  #   日期分类与数量
    context['page_range'] = page_range
    return context
Ejemplo n.º 59
0
def proposedClubList(request):
    voter=request.user
    totalstudent=Profile.objects.all().count()
    clubs = Onpollclub.objects.all()
    for i in clubs:
        start=i.date
        milistart=int(time.mktime(start.timetuple())) * 1000
        #print(milistart)
        #print('nf')
        currtime=timezone.now()
        milicurr=(int(time.mktime(currtime.timetuple())) * 1000) + 330*60*1000
        #print(milicurr)
        endtime=int(milistart) + 7*24*60*60*1000
        timeleft=int(endtime - milicurr)
        #print(timeleft)
        i.pollend=timeleft
        i.save()
        for a in clubs:
            if a.pollend<0:
                vote=a.num_vote_up
            #   print(vote)
                threshhold=(vote/totalstudent)*100
                if threshhold >10:
                    instance=ExistingClub.objects.create(club_name=a.club_name, club_info=a.club_info,club_logo=a.club_logo)
                    instance.admin.add(a.name)
                    instance.club_members.add(a.name)
                a.delete()

    clubs = Onpollclub.objects.all()
    paginator = Paginator(clubs,10)
    page = request.GET.get('page')
    posts = paginator.get_page(page)
    context = {
        'clubs': clubs,
    }
    return render(request,'propose_join/prlist.html', context)
Ejemplo n.º 60
0
def store_beers(request, store_id):
    '''
    Returns all beers in stock at given Vinmonopolet store
    Paginated in order to use infinite scroll
    '''
    
    queryset = BeerStock.objects.filter(product_stock__gt=0, store_id=store_id).order_by(F('beer_id__untappd__rating').desc(nulls_last=True))
    
    if request.user.is_authenticated:
        
        # This subquery returns the rating of any beers the User has checked in to Untappd
        check_in_subquery = UserCheckIn.objects.filter(beer_id = OuterRef('beer_id'), user_id=request.user)
        queryset = queryset.annotate(untappd_rating=Subquery(check_in_subquery.values('rating')[:1]))
        
        # This subquery returns a value if User has the Beer in Wish List on Untappd
        wishlist_subquery = UserWishList.objects.filter(beer_id = OuterRef('beer_id'), user_id=request.user)
        queryset = queryset.annotate(untappd_wishlist=Subquery(wishlist_subquery.values('user')[:1]))

    paginator = Paginator(queryset, 50, 0)

    page_number = request.GET.get('page')
    beerstock = paginator.get_page(page_number)

    return render(request, 'stubs/store_inventory.html', {'beerstock': beerstock, 'store_id': store_id, 'full_store_stock':True})