Example #1
0
def search_googleplay(request):
    api = GooglePlay().auth()
    myToken = csrf(request)
    if request.method == "POST":
        form = SearchForm(request.POST)
        if form.is_valid():
            searchterms = request.POST["terms"]
            appsFound = api.search(searchterms)
            appsFound.sort(key=lambda app: dirtybastard(app.details.appDetails.numDownloads), reverse=True)
            # appsDict = api.toDict(appsFound)
            # appsFound.sort(key=lambda app: app.details.appDetails.numDownloads)
            paginator = Paginator(appsFound, 20)
            page = request.GET.get("page")
            try:
                last_packages = paginator.page(page)
            except PageNotAnInteger:
                last_packages = paginator.page(1)
            except EmptyPage:
                last_packages = paginator.page(paginator.num_pages)
            context = {"packages": last_packages}
            return render_to_response("frontpage/gpresults.html", RequestContext(request, context))
        else:
            return HttpResponseRedirect("frontpage/search_source.html/", myDict)
    else:
        myToken = csrf(request)
        form = SearchForm()
        myDict = {"form": form, "title": "Buscar en Google Play"}
        myDict.update(myToken)
        return render_to_response("frontpage/search_source.html/", myDict)
Example #2
0
def history(request, source, page, page_rows=10, template_name="history.html"):

    if not request.user.is_authenticated():
        return HttpResponse("Must be logged in to see query history", status=403)

    queries = AdvancedQuery.objects.filter(user=request.user, removed=False).order_by("-date")

    ## Paginator ##
    if request.method == "POST":
        try:
            page_rows = int(request.POST.get("paginator_rows", 10))

            request.session["paginator_rows"] = page_rows
        except:
            pass
    else:
        try:
            page_rows = int(request.session["paginator_rows"])
        except:
            pass

    simple_queries = QueryLog.objects.filter(user=request.user, removed=False).order_by("-created_date")

    myPaginator = Paginator(simple_queries, page_rows)

    myadvancedPaginator = Paginator(queries, page_rows)

    if source == "0":
        try:
            pager_simple = myPaginator.page(page)
        except PageNotAnInteger, e:
            pager_simple = myPaginator.page(1)

        pager = myadvancedPaginator.page(1)
Example #3
0
    def __init__(self, format, request, data, **kwargs):
        if "detail_level" in kwargs:
            self.detail_level = kwargs["detail_level"]

        serialiser = get_serialiser(format, self.detail_level)
        mimetype = MIME_TYPES[format]

        if isinstance(data, Exception):
            super(APIResponse, self).__init__(serialiser.serialise(data), mimetype=mimetype)

            self.status_code = 500
            return

        if isinstance(data, QuerySet):
            page = request.GET.get("page", 1)
            rpp = request.GET.get("rpp", 100)

            try:
                rpp = int(rpp)
            except ValueError:
                return APIResponse(Exception("rpp not an integer"))

            paginator = Paginator(data, rpp)

            try:
                data = paginator.page(page)
            except EmptyPage:
                data = None
            except PageNotAnInteger:
                return APIResponse(Exception("page not an integer"))

            if data:
                data = data.object_list

        super(APIResponse, self).__init__(serialiser.serialise(data), mimetype=mimetype)
def get_details_list(request):
    pagenumber = request.GET.get("pagenumber", 1)
    work_id = request.POST.get("work_id")
    work = Works.objects.get(pk=int(work_id))

    query = Details.objects.filter(is_active=True, work=work).order_by("-date")

    query_paginated = Paginator(query, 30)
    query = query_paginated.page(pagenumber)
    next_page = None
    if query.has_next():
        next_page = query.next_page_number()

    works = []
    for work in query:
        works.append(
            {
                "id": work.id,
                "date": work.date,
                "expectedDate": work.expected_date,
                "actualDate": work.actual_date,
                "trialDate": work.trial_date,
                "qcDate": work.qc_date,
                "actionTaken": work.action_taken,
                "status": work.status,
                "cost": work.cost,
                "remarks": work.remarks,
            }
        )

    return JsonResponse({"works": works, "next_page": next_page})
Example #5
0
def messages_view(request):
    shopuser = ShopUser.from_request(request)
    shopinfo = ShopInfo()
    context = {"shopinfo": shopinfo, "shopuser": shopuser}
    if request.method == "POST":
        Message.objects.create(
            characterid=shopuser.characterid,
            name=shopuser.name,
            read_by_customer=True,
            read_by_handler=False,
            handler=None,
            text=request.POST.get("text", ""),
        )
        return HttpResponseRedirect("/shop/messages/")
    message_list = Message.objects.filter(characterid=shopuser.characterid)
    paginator = Paginator(message_list, 10)
    try:
        pagenum = int(request.GET.get("page", None))
    except (ValueError, TypeError):
        pagenum = paginator.num_pages
    try:
        page = paginator.page(pagenum)
    except (EmptyPage, InvalidPage):
        page = paginator.page(paginator.num_pages)
    context["is_paginated"] = True
    context["page_obj"] = page
    context["message_list"] = page.object_list
    for message in page.object_list:
        message.read_by_customer = True
        message.save()
    return direct_to_template(request, "shop/messages.html", extra_context=context)
Example #6
0
def search(request):
    page = Page.objects.get(name="search")
    query = request.GET.get("q")
    if not query or query.split() == "":
        return redirect(reverse("all_quote"))
    try:
        page_number = int(request.GET.get("page"))
        if page_number < 1:
            return redirect(reverse("search") + "?page=%s&q=%s" % (1, query))
    except:
        page_number = 1

    quotes = Quote.objects.filter(Q(content__contains=query) | Q(tags__name__contains=query))

    p = Paginator(quotes, page_count)
    pagination = p.page(page_number)

    collections = Collection.objects.all().order_by("-id")
    page.title = 'Search result for "%s"' % query
    return render(
        request,
        "all.html",
        {
            "page": page,
            "query": query,
            "pagination": pagination,
            "collections": collections,
            "prev_link": reverse("search") + "?page=%s&q=%s" % (page_number + 1, query),
            "next_link": reverse("search") + "?page=%s&q=%s" % (page_number - 1, query),
        },
    )
Example #7
0
def collection(request, collection_name):
    collection_name = collection_name.replace("-", " ").lower()
    try:
        page_number = int(request.GET.get("page"))
        if page_number < 1:
            return redirect(reverse("collection", collection_name) + "?page=%s" % (1))
    except:
        page_number = 1

    collection = Collection.objects.get(name__iexact=collection_name)
    quotes = Quote.objects.filter(collections__id__contains=collection.id).order_by("-id")
    p = Paginator(quotes, page_count)
    pagination = p.page(page_number)

    collections = Collection.objects.all()

    page = collection
    return render(
        request,
        "all.html",
        {
            "page": page,
            "pagination": pagination,
            "collections": collections,
            "prev_link": reverse("collection", args=[collection_name]) + "?page=%s" % (page_number + 1),
            "next_link": reverse("collection", args=[collection_name]) + "?page=%s" % (page_number - 1),
        },
    )
Example #8
0
def content_type_use(request, content_type_app_name, content_type_model_name):
    try:
        content_type = ContentType.objects.get_by_natural_key(content_type_app_name, content_type_model_name)
    except ContentType.DoesNotExist:
        raise Http404

    p = request.GET.get("p", 1)

    page_class = content_type.model_class()

    # page_class must be a Page type and not some other random model
    if not issubclass(page_class, Page):
        raise Http404

    pages = page_class.objects.all()

    paginator = Paginator(pages, 10)

    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)

    return render(
        request,
        "wagtailadmin/pages/content_type_use.html",
        {"pages": pages, "app_name": content_type_app_name, "content_type": content_type, "page_class": page_class},
    )
Example #9
0
def history(request, count=15, uid=None):
    user = request.user
    client = None

    history = HistoryEntry.objects.filter(user=user).select_related("podcast")

    if uid:
        try:
            client = user.client_set.get(uid=uid)
        except Client.DoesNotExist as e:
            messages.error(request, str(e))

    # if a client was given, filter for it
    if client:
        history = history.filter(client=client)

    paginator = Paginator(history, count)

    page = request.GET.get("page")

    try:
        entries = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        entries = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        entries = paginator.page(paginator.num_pages)

    return render(request, "history.html", {"history": entries, "client": client, "page": page})
Example #10
0
    def filter_response(self, obj):
        """
        Given the response content, paginate and then serialize.

        The response is modified to include to useful data relating to the number
        of objects, number of pages, next/previous urls etc. etc.

        The serialised objects are put into `results` on this new, modified
        response
        """

        # We don't want to paginate responses for anything other than GET requests
        if self.method.upper() != "GET":
            return self._resource.filter_response(obj)

        paginator = Paginator(obj, self.get_limit())

        try:
            page_num = int(self.request.GET.get("page", "1"))
        except ValueError:
            raise ErrorResponse(status.HTTP_404_NOT_FOUND, {"detail": "That page contains no results"})

        if page_num not in paginator.page_range:
            raise ErrorResponse(status.HTTP_404_NOT_FOUND, {"detail": "That page contains no results"})

        page = paginator.page(page_num)

        serialized_object_list = self._resource.filter_response(page.object_list)
        serialized_page_info = self.serialize_page_info(page)

        serialized_page_info["results"] = serialized_object_list

        return serialized_page_info
Example #11
0
def index(request, parent_page_id=None):
    if parent_page_id:
        parent_page = get_object_or_404(Page, id=parent_page_id)
    else:
        parent_page = Page.get_first_root_node()

    pages = parent_page.get_children().prefetch_related("content_type")

    # Get page ordering
    ordering = request.GET.get("ordering", "title")
    if ordering not in ["title", "-title", "content_type", "-content_type", "live", "-live", "ord"]:
        ordering = "title"

    # Pagination
    if ordering != "ord":
        pages = pages.order_by(ordering)

        p = request.GET.get("p", 1)
        paginator = Paginator(pages, 50)
        try:
            pages = paginator.page(p)
        except PageNotAnInteger:
            pages = paginator.page(1)
        except EmptyPage:
            pages = paginator.page(paginator.num_pages)

    return render(
        request, "wagtailadmin/pages/index.html", {"parent_page": parent_page, "ordering": ordering, "pages": pages}
    )
Example #12
0
    def serve(self, request, *args, **kwargs):
        # Get entries
        entries = self.blog_entries

        # Filter by tag
        # tag = request.GET.get('tag')
        # if tag:
        #     blog_posts = entries.filter(tags__tag__slug=tag)

        per_page = 10
        page = request.GET.get("page")
        paginator = Paginator(entries, per_page)

        try:
            entries = paginator.page(page)
        except PageNotAnInteger:
            entries = paginator.page(1)
        except EmptyPage:
            entries = paginator.page(paginator.num_pages)

        return TemplateResponse(
            request,
            self.get_template(request, *args, **kwargs),
            context={"self": self, "blog_posts": entries, "per_page": per_page},
        )
Example #13
0
    def get_context(self, request):
        # Get posts
        posts = self.posts

        # Filter by tag
        tag = request.GET.get("tag")
        if tag:
            posts = posts.filter(tags__name=tag)

        # Filter by category
        cat = request.GET.get("cat")
        if cat:
            posts = posts.filter(category=cat)

        # Pagination
        page = request.GET.get("page")
        paginator = Paginator(posts, 10)  # Show 10 posts per page
        try:
            posts = paginator.page(page)
        except PageNotAnInteger:
            posts = paginator.page(1)
        except EmptyPage:
            posts = paginator.page(paginator.num_pages)

        # Update template context
        context = super(BlogIndexPage, self).get_context(request)
        context["posts"] = posts
        context["categories"] = BLOG_CATEGORIES
        context["selected_category"] = cat
        context["tags"] = self.tags
        context["selected_tag"] = tag
        return context
Example #14
0
def post_list(request):
    query_list = Post.objects.active()
    total_posts = query_list.count
    if request.user.is_staff or request.user.is_superuser:
        query_list = Post.objects.all()

    search_query = request.GET.get("q")
    if search_query:
        query_list = query_list.filter(
            Q(title__icontains=search_query)
            | Q(content__icontains=search_query)
            | Q(user__first_name__icontains=search_query)
            | Q(user__last_name__icontains=search_query)
        ).distinct()

    paginator = Paginator(query_list, 5)
    page_request_var = "page"
    page = request.GET.get("page")

    total_posts = paginator.count
    try:
        page_list = paginator.page(page)
    except PageNotAnInteger:
        page_list = paginator.page(1)
    except EmptyPage:
        page_list = paginator.page(paginator.num_pages)

    context = {
        "list": page_list,
        "page_title": "All Articles",
        "page_request_var": page_request_var,
        "all_articles": total_posts,
    }
    return render(request, "post_list.html", context)
Example #15
0
def author(request, author_name):
    author_name = author_name.replace("-", " ").lower()

    try:
        page_number = int(request.GET.get("page"))
        if page_number < 1:
            return redirect(reverse("author", author_name) + "?page=%s" % (1))
    except:
        page_number = 1

    author = Author.objects.get(name__iexact=author_name)

    page = author
    if page.title.strip() == "":
        page = Page.objects.get(name="author")
        page.title = "%s Quotes" % author.name

    quotes = Quote.objects.filter(author=author).order_by("-id")
    p = Paginator(quotes, page_count)
    pagination = p.page(page_number)

    collections = Collection.objects.all()

    return render(
        request,
        "all.html",
        {
            "page": page,
            "pagination": pagination,
            "collections": collections,
            "prev_link": reverse("author", args=[author_name]) + "?page=%s" % (page_number + 1),
            "next_link": reverse("author", args=[author_name]) + "?page=%s" % (page_number - 1),
        },
    )
Example #16
0
def topic(request, category, forum, topic):
    topic_form = TopicForm()
    message_form = MessageForm()

    topic = get_object_or_404(Topic, slug=topic)
    messages = Message.objects.filter(topic=topic)[1:]
    messageset = Message.objects.filter(topic=topic)[1:]

    page = request.GET.get("page")
    paginator = Paginator(messageset, 10)
    Topic.objects.filter(slug=topic).update(view_count=F("view_count") + 1)
    Forum.objects.filter(pk=topic.forum.pk).update(view_count=F("view_count") + 1)

    try:
        messages = paginator.page(page)
    except PageNotAnInteger:
        messages = paginator.page(1)
    except EmptyPage:
        messages = paginator.page(paginator.num_pages)

    return render(
        request,
        "forum/topic.html",
        {
            "topic": topic,
            "messages": messages,
            "messageset": messageset,
            "paginator": paginator,
            "topic_form": topic_form,
            "message_form": message_form,
        },
    )
Example #17
0
def tag(request, tag_name):
    tag_name = tag_name.replace("-", " ").lower()
    try:
        page_number = int(request.GET.get("page"))
        if page_number < 1:
            return redirect(reverse("tag", tag) + "?page=%s" % (1))
    except:
        page_number = 1

    quotes = Quote.objects.filter(tags__name__contains=tag_name).order_by("-id")

    p = Paginator(quotes, page_count)
    pagination = p.page(page_number)

    collections = Collection.objects.all().order_by("-id")
    try:
        page = Tag.objects.get(name__iexact=tag_name)
    except:
        page = Page.objects.get(name="tag")
        page.title = "%s Quotes" % tag_name.title()

    return render(
        request,
        "all.html",
        {
            "page": page,
            "pagination": pagination,
            "collections": collections,
            "prev_link": reverse("tag", args=[tag_name.replace(" ", "-")]) + "?page=%s" % (page_number + 1),
            "next_link": reverse("tag", args=[tag_name.replace(" ", "-")]) + "?page=%s" % (page_number - 1),
        },
    )
Example #18
0
def userfilter(request):
    form = StudentFilter()
    person = Person.objects.get(pk=request.session["personpk"])
    if person.role_id == 1:
        object_list = Person.objects.all().order_by("facility").order_by("verified")
    else:
        object_list = Person.objects.filter(facility_id=person.facility_id)

    if request.session["ulname"] != "all":
        if person.role_id == 1:
            object_list = Person.objects.filter(lname__icontains=request.session["ulname"])
        else:
            object_list = Person.objects.filter(facility_id=person.facility_id).filter(
                lname__icontains=request.session["ulname"]
            )

    if request.method == "POST":
        form = StudentFilter(request.POST)
        if form.is_valid():
            if form.cleaned_data["lname"] is None:
                request.session["ulname"] = "all"
            else:
                request.session["ulname"] = form.cleaned_data["lname"]
        return HttpResponseRedirect(reverse("register:userlist"))
    paginator = Paginator(object_list, 10)
    page = request.GET.get("page")
    try:
        staff = paginator.page(page)
    except PageNotAnInteger:
        staff = paginator.page(1)
    except EmptyPage:
        staff = paginator.page(paginator.num_pages)
    return render(request, "register/person_list.html", {"object_list": staff, "form": form})
Example #19
0
def all(request):
    page = Page.objects.get(name="all")
    try:
        page_number = int(request.GET.get("page"))
        if page_number < 1:
            return redirect(reverse("all_quote", tag) + "?page=%s" % (1))
    except:
        page_number = 1

    quotes = Quote.objects.all().order_by("-id")

    p = Paginator(quotes, page_count)
    pagination = p.page(page_number)
    collections = Collection.objects.all().order_by("-id")
    page.title = "All quotes"
    return render(
        request,
        "all.html",
        {
            "pagination": pagination,
            "page": page,
            "collections": collections,
            "prev_link": reverse("all_quote") + "?page=%s" % (page_number + 1),
            "next_link": reverse("all_quote") + "?page=%s" % (page_number - 1),
        },
    )
Example #20
0
File: api.py Project: sdornan/proto
    def get_search(self, request, **kwargs):
        self.method_check(request, allowed=["get"])
        self.is_authenticated(request)
        self.throttle_check(request)

        # Do the query.
        sqs = SearchQuerySet().models(self.Meta.object_class).load_all().auto_query(request.GET.get("q", ""))
        paginator = Paginator(sqs, 20)

        try:
            page = paginator.page(int(request.GET.get("page", 1)))
        except InvalidPage:
            raise Http404("Sorry, no results on that page.")

        objects = []

        for result in page.object_list:
            bundle = self.build_bundle(obj=result.object, request=request)
            bundle = self.full_dehydrate(bundle)
            objects.append(bundle)

        object_list = {"objects": objects}

        self.log_throttled_access(request)
        return self.create_response(request, object_list)
Example #21
0
def SearchActivity(request):
    limit = 6
    isOrganizer = False
    isAdmin = False
    if request.user.is_anonymous() == False:
        isOrganizer = is_organizer(request.user)
        isAdmin = is_admin(request.user)
    q = request.GET["q"]
    activities = (
        Activity.objects.filter(publishdate__isnull=False)
        .filter(atstatus=0)
        .filter(Q(atname__icontains=q) | Q(atorganizer__username__icontains=q))
        .order_by("-publishdate")
    )
    paginator = Paginator(activities, limit)
    page = request.GET.get("page")
    try:
        activities = paginator.page(page)
    except PageNotAnInteger:
        activities = paginator.page(1)
    except EmptyPage:
        activities = paginator.page(paginator.num_pages)
    return render_to_response(
        "templates/philosopher/homepage.html",
        {"activities": activities, "isOrganizer": isOrganizer, "isAdmin": isAdmin, "queryValue": q},
        context_instance=RequestContext(request),
    )
Example #22
0
def legacy_requests_view(request, rtype):
    """
    View to see legacy requests of rtype request type, which should be either
    'food' or 'maintenance'.
    """
    if not rtype in ["food", "maintenance"]:
        raise Http404
    requests_dict = []  # [(req, [req_responses]), (req2, [req2_responses]), ...]
    requests = TeacherRequest.objects.filter(request_type=rtype)
    request_count = requests.count()
    paginator = Paginator(requests, 50)

    page = request.GET.get("page")
    try:
        requests = paginator.page(page)
    except PageNotAnInteger:
        requests = paginator.page(1)
    except EmptyPage:
        requests = paginator.page(paginator.num_pages)
    for req in requests:
        requests_dict.append((req, TeacherResponse.objects.filter(request=req)))
    return render_to_response(
        "teacher_requests.html",
        {
            "page_name": "Legacy {rtype} Requests".format(rtype=rtype.title()),
            "requests_dict": requests_dict,
            "requests": requests,
            "request_type": rtype.title(),
            "request_count": request_count,
        },
        context_instance=RequestContext(request),
    )
def get_works_list(request):
    pagenumber = request.GET.get("pagenumber", 1)

    query = Works.objects.filter(is_active=True).order_by("-date")

    query_paginated = Paginator(query, 30)
    query = query_paginated.page(pagenumber)
    next_page = None
    if query.has_next():
        next_page = query.next_page_number()

    works = []
    for work in query:
        works.append(
            {
                "id": work.id,
                "toolNumber": work.tool_number,
                "jwNumber": work.jw_number,
                "date": work.date,
                "product": work.product,
                "description": work.description,
                "startDate": work.start_date,
                "targetDate": work.target_date,
                "doneBy": work.done_by,
                "actualDateOfCompletion": work.actual_date,
                "remarks": work.remarks,
                "cost": work.cost,
                "status": work.status,
            }
        )

    return JsonResponse({"works": works, "next_page": next_page})
Example #24
0
def mail_view(request, username=None, page_num=1):
    """
    mail view controller
    """
    id = request.GET.get("id", None)
    if id:
        # request to mark mail as read
        msg = PollsterMessage.objects.get(id=id)  # @UndefinedVariable
        if msg.to_user == request.user:
            # make sure the person who owns the message is marking it
            msg.read = True
            msg.save()
        else:
            return HttpResponseForbidden("Nope! :)")
        return HttpResponse(content="happy success!")

    # YOU CAN ONLY DO IT FOR URESELF
    if username != request.user.username:
        return HttpResponseRedirect("/profile/%s/mail/view/" % request.user.username)

    vars = {}

    messages = PollsterMessage.objects.filter(to_user=request.user)  # @UndefinedVariable
    vars["msgCount"] = messages.count()
    paginator = Paginator(messages.order_by("-date_created"), 20)
    vars["paginator"] = paginator
    vars["page"] = paginator.page(page_num)

    page_hash = paging_utils.setup_page_hash(
        paginator=paginator, page_num=page_num, page_link_prefix="/profile/%s/mail/view" % username
    )
    vars.update(page_hash)

    vars["messageForm"] = MessageForm()
    return base.render(request, "user/mailview.html", vars)
Example #25
0
def index_view(request):
    shopuser = ShopUser.from_request(request)
    shopinfo = ShopInfo()
    context = {"shopinfo": shopinfo, "shopuser": shopuser}
    if request.method == "POST":
        return add_to_cart(request, shopuser)
    context["needle"] = request.GET.get("search", None)
    if context["needle"] is None:
        context["needle"] = ""
        context["product_list"] = top_3()
        context["indexpage"] = True
    else:
        objects = ProductList.objects.filter(typename__icontains=context["needle"])
        paginator = Paginator(objects, 5)
        try:
            pagenum = int(request.GET.get("page", 1))
        except ValueError:
            pagenum = 1
        try:
            page = paginator.page(pagenum)
        except (EmptyPage, InvalidPage):
            page = paginator.page(paginator.num_pages)
        context["page"] = page
        context["product_list"] = page.object_list
    for product in context["product_list"]:
        product.multiplier = shopuser.multiplier
        product.discount = shopuser.discount
    return direct_to_template(request, "shop/index.html", extra_context=context)
Example #26
0
    def paginate_queryset(self, queryset, request, view=None):
        """Paginate a queryset if required, either returning a page object, or
        `None` if pagination is not configured for this view."""

        page_size = self.get_page_size(request)
        if not page_size:
            return None

        paginator = DjangoPaginator(queryset, page_size)
        page_number = request.query_params.get(self.page_query_param, 1)
        if page_number in self.last_page_strings:
            page_number = paginator.num_pages

        try:
            self.page = paginator.page(page_number)
            # we need to execute the query to resolve the page of objects
            self.page.object_list = self.page.object_list.execute()
        except InvalidPage as exc:
            msg = self.invalid_page_message.format(page_number=page_number, message=six.text_type(exc))
            raise NotFound(msg)
        except Exception as exc:
            # This probably came from ES, so let's log it, and return and
            # empty response to the client.  This can happen when the indices
            # have not been created, or generally on any ES exception.
            logger.exception(exc)
            self.page.object_list = ESResponse({"hits": {"hits": []}})

        if paginator.count > 1 and self.template is not None:
            # The browsable API should display pagination controls.
            self.display_page_controls = True

        self.request = request
        return self.page.object_list
Example #27
0
def search_article(request, page=1):
    if request.method == "POST":
        query = request.POST.get("query", None)
        if query == None:
            template = "articles/article_list.html"
        else:
            # return HttpResponse("you search "+query)
            r = Article.search.query(query)
            # listing articles with no particular filtering
            articles = list(r)
            context = {"articles": articles, "query": query, "search_meta": r._sphinx}
            template = "articles/article_search.html"

        # paginate the articles
        paginator = Paginator(articles, ARTICLE_PAGINATION, orphans=int(ARTICLE_PAGINATION / 4))
        try:
            page = paginator.page(page)
        except EmptyPage:
            raise Http404

        context.update({"paginator": paginator, "page_obj": page})
        variables = RequestContext(request, context)
        response = render_to_response(template, variables)

        return response
    else:
        # return HttpResponse("fuck off")
        raise Http404
Example #28
0
def enviar_mensaje(request):
    mensaje = Mensajero.objects.filter(user=request.user).order_by("-id")
    paginator = Paginator(mensaje, 5)
    page = request.GET.get("page")
    try:
        mensajes = paginator.page(page)
    except PageNotAnInteger:
        mensajes = paginator.page(1)
    except EmptyPage:
        mensajes = paginator.page(paginator.num_pages)

    if request.method == "POST":
        form = MensajeForm(request.POST)
        if form.is_valid():
            # form.save()
            form_uncommited = form.save(commit=False)
            form_uncommited.usuario = request.user
            # form_uncommited.user = form.cleaned_data['user']
            form_uncommited.save()
            form.save_m2m()

            thread.start_new_thread(notify_user_mensaje, (form_uncommited,))
            guardado = 1

            return HttpResponseRedirect("/contrapartes/mensaje/ver/?guardado=ok")

    else:
        form = MensajeForm()
    return render_to_response("contrapartes/mensaje.html", locals(), context_instance=RequestContext(request))
Example #29
0
def index(request, pagina):
    work_list = Trabalho.objects.all()

    paginator = Paginator(work_list, 9)

    try:
        lista = paginator.page(pagina)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        lista = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        lista = paginator.page(paginator.num_pages)

    servicos = []

    for l in lista:
        if not (servicos.__contains__(l.servico)):
            servicos.append(l.servico)

    tags = []

    for l in lista:
        for t in l.tags.all():
            if not (tags.__contains__(t)):
                tags.append(t)

    return render_to_response(
        "portfolio.html",
        {"trabalhos": lista, "servicos": servicos, "tags": tags},
        context_instance=RequestContext(request),
    )
Example #30
0
def user_management_context(request, facility_id, group_id, page=1, per_page=25):
    facility = Facility.objects.get(id=facility_id)
    groups = FacilityGroup.objects.filter(facility=facility)

    user_list = get_users_from_group(group_id, facility=facility)

    # Get the user list from the group
    if not user_list:
        users = []
    else:
        paginator = Paginator(user_list, per_page)
        try:
            users = paginator.page(page)
        except PageNotAnInteger:
            users = paginator.page(1)
        except EmptyPage:
            users = paginator.page(paginator.num_pages)

    if users:
        if users.has_previous():
            prevGETParam = request.GET.copy()
            prevGETParam["page"] = users.previous_page_number()
            previous_page_url = "?" + prevGETParam.urlencode()
        else:
            previous_page_url = ""
        if users.has_next():
            nextGETParam = request.GET.copy()
            nextGETParam["page"] = users.next_page_number()
            next_page_url = "?" + nextGETParam.urlencode()
        else:
            next_page_url = ""
    context = {"facility": facility, "users": users, "groups": groups}
    if users:
        context["pageurls"] = {"next_page": next_page_url, "prev_page": previous_page_url}
    return context