Here are the examples of the python api django.shortcuts.get_object_or_404 taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: symposion
Source File:
View license
def review_detail(request, pk):

    proposals = ProposalBase.objects.select_related("result").select_subclasses()
    proposal = get_object_or_404(proposals, pk=pk)

    if not request.user.has_perm("reviews.can_review_%s" % proposal.kind.section.slug):
        return access_not_permitted(request)

    speakers = [s.user for s in proposal.speakers()]

    if not request.user.is_superuser and request.user in speakers:
        return access_not_permitted(request)

    admin = request.user.is_staff

        latest_vote = LatestVote.objects.get(proposal=proposal, user=request.user)
    except LatestVote.DoesNotExist:
        latest_vote = None

    if request.method == "POST":
        if request.user in speakers:
            return access_not_permitted(request)

        if "vote_submit" in request.POST:
            review_form = ReviewForm(request.POST)
            if review_form.is_valid():

                review =
                review.user = request.user
                review.proposal = proposal

                return redirect(request.path)
                message_form = SpeakerCommentForm()
        elif "message_submit" in request.POST:
            message_form = SpeakerCommentForm(request.POST)
            if message_form.is_valid():

                message =
                message.user = request.user
                message.proposal = proposal

                for speaker in speakers:
                    if speaker and
                        ctx = {
                            "proposal": proposal,
                            "message": message,
                            "reviewer": False,
                            [], "proposal_new_message",

                return redirect(request.path)
                initial = {}
                if latest_vote:
                    initial["vote"] =
                if request.user in speakers:
                    review_form = None
                    review_form = ReviewForm(initial=initial)
        elif "result_submit" in request.POST:
            if admin:
                result = request.POST["result_submit"]

                if result == "accept":
                    proposal.result.status = "accepted"
                elif result == "reject":
                    proposal.result.status = "rejected"
                elif result == "undecide":
                    proposal.result.status = "undecided"
                elif result == "standby":
                    proposal.result.status = "standby"

            return redirect(request.path)
        initial = {}
        if latest_vote:
            initial["vote"] =
        if request.user in speakers:
            review_form = None
            review_form = ReviewForm(initial=initial)
        message_form = SpeakerCommentForm()

    proposal.comment_count = proposal.result.comment_count
    proposal.total_votes = proposal.result.vote_count
    proposal.plus_one = proposal.result.plus_one
    proposal.plus_zero = proposal.result.plus_zero
    proposal.minus_zero = proposal.result.minus_zero
    proposal.minus_one = proposal.result.minus_one

    reviews = Review.objects.filter(proposal=proposal).order_by("-submitted_at")
    messages = proposal.messages.order_by("submitted_at")

    return render(request, "symposion/reviews/review_detail.html", {
        "proposal": proposal,
        "latest_vote": latest_vote,
        "reviews": reviews,
        "review_messages": messages,
        "review_form": review_form,
        "message_form": message_form

Example 2

Project: product-definition-center
Source File:
View license
    def create(self, request):
        Clone an existing release identified by `old_release_id`. Currently the
        release, its variants and arches will be cloned. Also, all release
        components associated with the release will be cloned.

        __Method__: POST

        __URL__: $LINK:releaseclone-list$


                "old_release_id":               string,
                "short":                        string,     # optional
                "version":                      string,     # optional
                "name":                         string,     # optional
                "release_type":                 string,     # optional
                "base_product":                 string,     # optional
                "active":                       bool,       # optional
                "product_version":              string,     # optional
                "dist_git": {
                    "branch":                   string
                },                                          # optional
                "bugzilla": {
                    "product":                  string
                },                                          # optional
                "component_dist_git_branch":    string,     # optional
                "include_inactive":             bool,       # optional
                "include_trees":                [string],   # optional
                "integrated_with:               string      # optional

        The changed attributes must yield a different release_id, therefore
        change in at least one of `short`, `version`, `base_product` or
        `release_type` is required.

        If `component_dist_git_branch` is present, it will be set for all
        release components under the newly created release. If missing, release
        components will be cloned without changes.

        If `include_inactive` is False, the inactive release_components belong to
        the old release won't be cloned to new release.
        Default it will clone all release_components to new release.

        If `include_tree` is specified, it should contain a list of
        Variant.Arch pairs that should be cloned. If not given, all trees will
        be cloned. If the list is empty, no trees will be cloned.
        data =
        if 'old_release_id' not in data:
            return Response({'__all__': 'Missing old_release_id'},
        old_release_id = data.pop('old_release_id')
        old_release = get_object_or_404(models.Release, release_id=old_release_id)

        old_data = ReleaseSerializer(instance=old_release).data

        for (field_name, field) in ReleaseSerializer().fields.iteritems():
            if not field.read_only and field_name not in data:
                value = old_data.get(field_name, None)
                if value:
                    data[field_name] = value

        for key in data.keys():
            if data[key] is None:

        serializer = ReleaseSerializer(data=data,

        new_release =
                              'null', json.dumps(new_release.export()))


        return Response(, status=status.HTTP_201_CREATED)

Example 3

Project: product-definition-center
Source File:
View license
    def create(self, request):
        Clone all content delivery repositories from one release under another release.

        The call is atomic, i.e. either all content delivery repositories are cloned or nothing
        is done.

        If the source and target releases do not have the same variants, the
        cloning will silently ignore content delivery repositories with Variant.Arch that is
        present in source release but not in target release. It is not a
        problem if the target release has additional variants.

        __Method__: `POST`

        __URL__: $LINK:cdreposclone-list$


                "release_id_from":          string,
                "release_id_to":            string
                "include_service":          [string],   # optional
                "include_repo_family":      [string],   # optional
                "include_content_format":   [string],   # optional
                "include_content_category": [string],   # optional
                "include_shadow":           bool,       # optional
                "include_product_id":       int         # optional

        The `include_*` keys are used to filter which releases should be
        cloned. If any key is omitted, all values for that attribute will be

        The call returns a list of content delivery repositories created under target release.

                "shadow":           bool,
                "release_id":       string,
                "variant_uid":      string,
                "arch":             string,
                "service":          string,
                "repo_family":      string,
                "content_format":   string,
                "content_category": string,
                "name":             string,
                "product_id":       int
        data =
        keys = set(['release_id_from', 'release_id_to'])
        arg_filter_map = {'include_service': ('service__name__in', hacks.as_list),
                          'include_repo_family': ('repo_family__name__in', hacks.as_list),
                          'include_content_format': ('content_format__name__in', hacks.as_list),
                          'include_content_category': ('content_category__name__in', hacks.as_list),
                          'include_shadow': ('shadow', hacks.convert_str_to_bool),
                          'include_product_id': ('product_id', hacks.convert_str_to_int)}
        allowed_keys = list(keys) + arg_filter_map.keys()

        missing_keys = keys - set(data.keys())
        if missing_keys:
            errors = dict([(k, ['This field is required.']) for k in missing_keys])
            return Response(status=status.HTTP_400_BAD_REQUEST, data=errors)
        extra_keys = set(data.keys()) - set(allowed_keys)

        get_object_or_404(Release, release_id=data['release_id_from'])
        target_release = get_object_or_404(Release, release_id=data['release_id_to'])

        kwargs = {
            'variant_arch__variant__release__release_id': data['release_id_from']

        for arg, (filter, transform) in arg_filter_map.iteritems():
            arg_data =
            if arg_data:
                kwargs[filter] = transform(arg_data, name=arg)

        repos = models.Repo.objects.filter(**kwargs)

        # Skip repos from nonexisting trees.
        repos_in_target_release = [repo for repo in repos if repo.tree in target_release.trees]

        if not repos or not repos_in_target_release:
            return Response(status=status.HTTP_400_BAD_REQUEST,
                            data={'detail': 'No repos to clone.'})

        serializer = serializers.RepoSerializer(repos_in_target_release, many=True)
        copy =
        for repo in copy:
            # The serializer will reject read-only fields, so we need to drop the id.
            del repo['id']
            repo['release_id'] = target_release.release_id
        new_repos = serializers.RepoSerializer(data=copy, many=True)
        if not new_repos.is_valid():
            return Response(status=status.HTTP_400_BAD_REQUEST,
                            data={'detail': dict((repo['name'], err)
                                                 for repo, err in zip(copy, new_repos.errors)
                                                 if err)})
        for raw_repo, repo_obj in zip(copy,
                                  'null', json.dumps(raw_repo))

        return Response(status=status.HTTP_200_OK,

Example 4

Project: pycon
Source File:
View license
def proposal_detail(request, proposal_id):
    """Retrieve and return information about the given proposal, or
    if this is a POST request, write the appropriate data instead.

    Requires an API key.

    URL:  /<year>/pycon_api/proposals/DD/

    where `DD` is the key for the desired proposal. Keys can be found
    using the proposals_list API.

    On a GET, the data returned is JSON that looks like the data from
    the proposals_list API, with some additional fields::

            'id': 13,  # proposal key
            'speakers': [<speaker>, <speaker>, ..., <speaker>],
            'status': "undecided"|"accepted"|"rejected"|"standby"
            'title': "Title of talk",
            'details': {
                'abstract': "abstract",
                'description': "description",
                'notes': "additional notes"
            'extra': 'BLOB'   # Only if this API has been used to set extra data

    If no extra data has been set, the 'extra' key is not present.

    If the method is POST and the body is a dictionary, the API allows updating
    a limited part of the data in the proposal as follows:

            If the value is one of 'accepted', 'rejected', 'standby', or 'undecided',
            update the proposal's status to the new value
            If the value is the code for a thunderdome group, the proposal is added
            to the specified group.

    Anything else in the dictionary is ignored.

    If the body is not a dictionary, then it is stored as the 'extra'
    data for the proposal, and will be returned when the proposal is retrieved
    again using this API.
    # Retrieve the proposal.
    proposal = get_object_or_404(ProposalBase, pk=int(proposal_id))

    # If this is a POST request, then we are **setting** data
    # on this proposal; do that.
    if request.method == 'POST':
        # For some bizarre reason that I cannot comprehend, request.body
        # has to be loaded twice.
        data = json.loads(request.body)
        if isinstance(data, (str, unicode)):
            data = json.loads(data)

        # If we get a dictionary (which will be the normal case), then 
        # look for certain "special" keys, and if we get them, we alter some
        # status on the proposal itself.
        if isinstance(data, dict):
            # Check for the "status" key.  This assigns the given status
            # to the proposal.
            status = data.pop('status', None)
            if status:
                # Sanity check: Is this a valid value?
                if status not in ('accepted', 'rejected',
                                  'standby', 'undecided'):
                    return ({ 'error': 'Invalid status.' }, 400)

                proposal.result.status = status

            # Check for the "thunderdome_group" key.  This assigns the
            # given thunderdome group to the proposal.
            td_group_code = data.pop('thunderdome_group', None)
            if td_group_code:
                    td_group = ThunderdomeGroup.objects.get(code=td_group_code)
                except ThunderdomeGroup.DoesNotExist:
                    return ({ 'error': 'Invalid thunderdome group.' }, 400)

                proposal.pycontalkproposal.thunderdome_group = td_group

        # Anything else just becomes arbitrary proposal data.
        pd, new = ProposalData.objects.get_or_create(proposal=proposal) = json.dumps(data)

        # Return a success.
        return ({ 'message': 'Proposal updated.' }, 202)

    # Return a dictionary representation of the proposal.
        return proposal.pycontalkproposal.as_dict(details=True)
    except PyConTalkProposal.DoesNotExist:
        return proposal.as_dict(details=True)

Example 5

Project: pycon
Source File:
View license
def review_detail(request, pk):

    proposals = ProposalBase.objects.select_related("result").select_subclasses()
    proposal = get_object_or_404(proposals, pk=pk)

    if not request.user.has_perm("reviews.can_review_%s" % proposal.kind.section.slug):
        return access_not_permitted(request)

    speakers = [s.user for s in proposal.speakers()]

    if not request.user.is_superuser and request.user in speakers:
        return access_not_permitted(request)

    admin = request.user.is_staff

        latest_vote = LatestVote.objects.get(proposal=proposal, user=request.user)
    except LatestVote.DoesNotExist:
        latest_vote = None

    review_form = None
    message_form = None
    proposal_tags_form = None

    if request.method == "POST":
        if request.user in speakers:
            return access_not_permitted(request)

        if "vote_submit" in request.POST \
                and (is_voting_period_active(proposal) or is_review_period_active(proposal)):
            if is_voting_period_active(proposal):
                review_form = ReviewForm(request.POST)
                review_form = NonVotingReviewForm(request.POST)
            if review_form.is_valid():

                review =
                review.user = request.user
                review.proposal = proposal

                return redirect(request.path)
                message_form = SpeakerCommentForm()
        elif "tags_submit" in request.POST:
            proposal_tags_form = ProposalTagsForm(request.POST)
            if proposal_tags_form.is_valid():

                tags = proposal_tags_form.cleaned_data['tags']

                return redirect(request.path)
                message_form = SpeakerCommentForm()
                if request.user not in speakers:
                    initial = {}
                    if latest_vote:
                        initial["vote"] =

                    if is_voting_period_active(proposal):
                        review_form = ReviewForm(initial=initial)
                    elif is_review_period_active(proposal):
                        review_form = NonVotingReviewForm()
        elif "message_submit" in request.POST and is_review_period_active(proposal):
            message_form = SpeakerCommentForm(request.POST)
            if message_form.is_valid():

                message =
                message.user = request.user
                message.proposal = proposal

                for speaker in speakers:
                    if speaker and
                        ctx = {
                            "proposal": proposal,
                            "message": message,
                            "reviewer": False,
                            [], "proposal_new_message",

                return redirect(request.path)
                initial = {}
                if latest_vote:
                    initial["vote"] =
                if request.user not in speakers:
                    if is_voting_period_active(proposal):
                        review_form = ReviewForm(initial=initial)
                    elif is_review_period_active(proposal):
                        review_form = NonVotingReviewForm()
        elif "result_submit" in request.POST:
            if admin:
                result = request.POST["result_submit"]

                if result == "accept":
                    proposal.result.status = "accepted"
                elif result == "reject":
                    proposal.result.status = "rejected"
                elif result == "undecide":
                    proposal.result.status = "undecided"
                elif result == "standby":
                    proposal.result.status = "standby"

            return redirect(request.path)
        initial = {}
        if latest_vote:
            initial["vote"] =
        if request.user not in speakers:
            if is_voting_period_active(proposal):
                review_form = ReviewForm(initial=initial)
            elif is_review_period_active(proposal):
                review_form = NonVotingReviewForm()
            tags = edit_string_for_tags(proposal.tags.all())
            proposal_tags_form = ProposalTagsForm(initial={'tags': tags})
        if is_review_period_active(proposal) and request.user not in speakers:
            message_form = SpeakerCommentForm()

    proposal.comment_count = proposal.result.comment_count
    proposal.total_votes = proposal.result.vote_count
    proposal.plus_one = proposal.result.plus_one
    proposal.plus_zero = proposal.result.plus_zero
    proposal.minus_zero = proposal.result.minus_zero
    proposal.minus_one = proposal.result.minus_one

    reviews = Review.objects.filter(proposal=proposal).order_by("-submitted_at")
    messages = proposal.messages.order_by("submitted_at")

    return render(request, "reviews/review_detail.html", {
        "proposal": proposal,
        "latest_vote": latest_vote,
        "reviews": reviews,
        "review_messages": messages,
        "review_form": review_form,
        "proposal_tags_form": proposal_tags_form,
        "message_form": message_form,

Example 6

Project: junction
Source File:
View license
def proposals_dashboard(request, conference_slug):
    conference = get_object_or_404(Conference, slug=conference_slug)

    if not is_conference_moderator(user=request.user, conference=conference):
        raise PermissionDenied

    proposals_qs = Proposal.objects.filter(

    by_type = {}
    by_section = {}
    by_reviewer = {}
    by_audience = {}
    reviewed_count = 0
    unreviewed_count = 0
    for proposal in proposals_qs:
        pro_type = proposal.proposal_type
        section = proposal.proposal_section
        # dict structure {'id':[total, review, unreview, name]}
        by_type.setdefault(, [0, 0, 0,])
        by_type[][0] = by_type[][0] + 1
        by_section.setdefault(, [0, 0, 0,])
        by_section[][0] = by_section[][0] + 1
        private_comment_count = \
        if private_comment_count:
            reviewed_count = reviewed_count + 1
            by_type[][1] = by_type[][1] + 1
            by_section[][1] = by_section[][1] + 1
            unreviewed_count = unreviewed_count + 1
            by_type[][2] = by_type[][2] + 1
            by_section[][2] = by_section[][2] + 1
    sections = \
    # Hande case if reviewer is added to section twice'

    for section in sections:
        proposal_qs = proposals_qs.filter(
        # due to space and number issue for key used this
        key_id = '%s' %
            [proposal_qs.count(), 0, 0,])
        for proposal in proposal_qs:
            private_comment_count = ProposalComment.objects.filter(
                proposal=proposal, deleted=False, private=True).count()
            if private_comment_count:
                by_reviewer[key_id][1] = by_reviewer[key_id][1] + 1
                by_reviewer[key_id][2] = by_reviewer[key_id][2] + 1

    audience_dict = {
        1: 'Beginner',
        2: 'Intermediate',
        3: 'Advanced'

    for proposal in proposals_qs:
        audience = audience_dict[proposal.target_audience]
        by_audience.setdefault(audience, [0, 0, 0, audience])
        private_comment_count = \
        if private_comment_count:
            by_audience[audience][1] = by_audience[audience][1] + 1
            by_audience[audience][0] = by_audience[audience][0] + 1
            by_audience[audience][2] = by_audience[audience][2] + 1
            by_audience[audience][0] = by_audience[audience][0] + 1

    ctx = {
        'conference': conference,
        'total': proposals_qs.count(),
        'reviewed': reviewed_count,
        'unreviewed': unreviewed_count,
        'group_by_type': by_type,
        'group_by_section': by_section,
        'group_by_reviewer_section': by_reviewer,
        'by_target_audience': by_audience
    return render(request, 'proposals/dashboard.html', ctx)

Example 7

Project: junction
Source File:
View license
def detail_proposal(request, conference_slug, slug, hashid=None):
    """Display a proposal detail page.
    # Here try to get a proposal by it's hashid. If the slug didn't match because
    # the title might have changed, redirect to the correct slug.
    # hashid is optional due to backward compatibility. If the hashid is not present
    # we still try to get the proposal by old method i.e. using just the slug, but
    # redirect to the correct url containing hashid.
    hashids = Hashids(min_length=5)
    id = hashids.decode(hashid)
    if id:
        proposal = get_object_or_404(Proposal, id=id[0])
        if slug != proposal.get_slug():
            return HttpResponseRedirect(proposal.get_absolute_url())
        conference = get_object_or_404(Conference, slug=conference_slug)
        proposal = get_object_or_404(Proposal, slug=slug, conference=conference)
        return HttpResponseRedirect(proposal.get_absolute_url())

    # Here we have obtained the proposal that we want to display.
    conference = proposal.conference
    read_private_comment = permissions.is_proposal_author_or_proposal_reviewer(
        request.user, conference, proposal)
    write_private_comment = permissions.is_proposal_author_or_proposal_section_reviewer(
        request.user, conference, proposal)
    is_reviewer = permissions.is_proposal_reviewer(request.user, conference)
    is_section_reviewer = permissions.is_proposal_section_reviewer(
        request.user, conference, proposal)
    public_voting = ConferenceSettingConstants.ALLOW_PUBLIC_VOTING_ON_PROPOSALS
    public_voting_setting = conference.conferencesetting_set.filter(
    vote_value, public_voting_setting_value = 0, True

    if public_voting_setting:
        public_voting_setting_value = public_voting_setting.value
            if request.user.is_authenticated():
                proposal_vote = ProposalVote.objects.get(proposal=proposal, voter=request.user)
                vote_value = 1 if proposal_vote.up_vote else -1
        except ProposalVote.DoesNotExist:

    ctx = {
        'login_url': settings.LOGIN_URL,
        'proposal': proposal,
        'read_private_comment': read_private_comment,
        'write_private_comment': write_private_comment,
        'vote_value': vote_value,
        'is_author': request.user ==,
        'is_reviewer': is_reviewer,
        'is_section_reviewer': is_section_reviewer,
        'can_view_feedback': False,
        'can_vote': permissions.is_proposal_voting_allowed(proposal),
        'public_voting_setting': public_voting_setting_value

    if proposal.scheduleitem_set.all():
        schedule_item = proposal.scheduleitem_set.all()[0]
        ctx['can_view_feedback'] = feedback_permission.can_view_feedback(user=request.user,
        ctx['schedule_item'] = schedule_item

    comments = ProposalComment.objects.filter(proposal=proposal, deleted=False, vote=False)

    if read_private_comment:
        ctx['reviewers_comments'] = comments.get_reviewers_comments()
    if write_private_comment:
        ctx['reviewers_proposal_comment_form'] = ProposalCommentForm(initial={'private': True})
    if is_reviewer:
        ctx['reviewers_only_proposal_comment_form'] = ProposalCommentForm(initial={'reviewer': True})
        ctx['reviewers_only_comments'] = comments.get_reviewers_only_comments()

    ctx.update({'comments': comments.get_public_comments(),
                'proposal_comment_form': ProposalCommentForm()})

    return render(request, 'proposals/detail/base.html', ctx)

Example 8

Project: django-yarr
Source File:
View license
def feed_form(
    request, feed_pk=None, template_add="yarr/feed_add.html",
    template_edit="yarr/feed_edit.html", success_url=None,
    Add or edit a feed
    # Detect whether it's add or edit
    if feed_pk is None:
        is_add = True
        form_class = forms.AddFeedForm
        feed = models.Feed()
        title = "Add feed"
        template = template_add
        is_add = False
        form_class = forms.EditFeedForm
        feed = get_object_or_404(models.Feed, user=request.user, pk=feed_pk)
        title = "Edit feed"
        template = template_edit
    # Process request
    if request.POST:
        feed_form = form_class(request.POST, instance=feed)
        if feed_form.is_valid():
            # Save changes
            if is_add:
                # Save feed
                # ++ Really we would like to get the feed at this point, to
                # ++ fill out the name and other feed details, and grab initial
                # ++ entries. However, feedparser isn't thread-safe yet, so for
                # ++ now we just have to wait for the next scheduled check
                feed =
                feed.title = feed.feed_url
                feed.user = request.user
                feed =
            # Report and redirect
            if success_url is None:
                    'Feed added.' if is_add else 'Changes saved',
            return HttpResponseRedirect(
                reverse('yarr-feeds') if success_url is None else success_url
    elif 'feed_url' in request.GET:
        feed_form = form_class(request.GET, instance=feed)
        feed_form = form_class(instance=feed)
    return render(request, template, {
        'title':    title,
        'feed_form': feed_form,
        'feed':     feed,

Example 9

Project: rapidsms
Source File:
View license
def locations(req, location_uid=None):
    view_location = None

    if location_uid is not None:
        view_location = Location.get_for_uid(

    if req.method == "POST":
        model_class = utils.get_model(req.POST["type"])
        form_class = utils.form_for_model(model_class)
        model = None

        if req.POST.get("id", None):
            model = get_object_or_404(
                model_class, pk=req.POST["id"])

            if req.POST["submit"] == "Delete":
                return HttpResponseRedirect(

        form = form_class(instance=model, data=req.POST)

        if form.is_valid():
            model =

            if req.POST.get("parent_type", None) and req.POST.get(
                    "parent_id", None):
                parent_class = utils.get_model(req.POST["parent_type"])
                parent = get_object_or_404(parent_class,
                model.parent = parent

                return HttpResponseRedirect(
                    reverse(locations, args=(parent.uid,)))

            return HttpResponseRedirect(

    types = [
        LocationTypeStub(type, req, view_location)
        for type in Location.subclasses()]

    return render_to_response(
        "locations/dashboard.html", {
            "breadcrumbs": _breadcrumbs(view_location),
            "location": view_location,
            "location_types": types,

            # from rapidsms.contrib.locations.settings
            "default_latitude": settings.MAP_DEFAULT_LATITUDE,
            "default_longitude": settings.MAP_DEFAULT_LONGITUDE,

            # if there are no locationtypes, then we should display a
            # big error, since this app is useless without them.
            "no_location_types": (len(types) == 0)
        }, context_instance=RequestContext(req)

Example 10

Project: Observatory
Source File:
View license
def modify(request, project_url_path, tab_id = 1):
  # redirect if the url path is not in the correct format
  resp = force_url_paths(modify, project_url_path)
  if resp: return resp
  project = get_object_or_404(Project, url_path = project_url_path)
  screenshots = Screenshot.objects.filter(project = project)
  # if someone tries to edit a project they shouldn't be able to
  if not (request.user in project.authors.all() or
    return HttpResponseRedirect(reverse(show, args = (project.url_path,)))
  # default forms
  project_form = ProjectForm(instance = project)
  cloned_repo_form = ClonedRepositoryForm(instance = project.repository)
  feed_repo_form = FeedRepositoryForm(instance = project.repository)
  blog_form = BlogForm(instance =
  screenshot_form = UploadScreenshotForm()
  # if changes should be saved or rejected
  if request.POST:
    # uploading a screenshot
    if 'screenshot_upload' in request.POST:
      form = UploadScreenshotForm(request.POST, request.FILES)
      if form.is_valid():
        Screenshot.create(form, request.FILES["file"], project)
        screenshot_form = form

    # wrote a post with the js overlay
    if 'title' in request.POST and 'markdown' in request.POST:
      from dashboard.views.blogs import create_post_real
      return create_post_real(request.POST)

    # editing the project's information
    elif 'title' in request.POST:
      form = ProjectForm(request.POST)
      # if the form is valid, save
      if form.is_valid():
        project.title = form.cleaned_data['title'] = form.cleaned_data['website'] = form.cleaned_data['wiki']
        project.description = form.cleaned_data['description'] = form.cleaned_data['active']
        project_form = ProjectForm(instance = project)
      # otherwise, display the errors
        project_form = form
    # editing a cloned repository
    elif 'clone_url' in request.POST:
      form = ClonedRepositoryForm(request.POST)
      if form.is_valid():
        project.repository.web_url = form.cleaned_data['web_url']
        project.repository.clone_url = form.cleaned_data['clone_url']
        project.repository.vcs = form.cleaned_data['vcs']
        project.repository.from_feed = False
        cloned_repo_form = ClonedRepositoryForm(instance = project.repository)
        cloned_repo_form = form
    # editing a feed repository
    elif 'repo_rss' in request.POST:
      form = FeedRepositoryForm(request.POST)
      if form.is_valid():
        project.repository.repo_rss = form.cleaned_data['repo_rss']
        project.repository.cmd = form.cleaned_data['cmd']
        project.repository.web_url = form.cleaned_data['web_url']
        project.repository.from_feed = True
        feed_repo_form = FeedRepositoryForm(instance = project.repository)
        feed_repo_form = form
    # editing a feed-based blog
    elif 'url' in request.POST:
      form = BlogForm(request.POST)
      if form.is_valid(): = form.cleaned_data['url'] = form.cleaned_data['rss'] = True
        blog_form = BlogForm(instance =
        blog_form = form
    # switching to hosted blog
    elif 'switch-to-hosted' in request.POST: = False
  return render_to_response('projects/modify.html', {
    'project': project,
    'screenshots': screenshots,
    'project_form': project_form,
    'cloned_repo_form': cloned_repo_form,
    'feed_repo_form': feed_repo_form,
    'blog_form': blog_form,
    'screenshot_form': screenshot_form,
    'post_form': BlogPostForm(),
    'repo': project.repository,
    'tab': int(tab_id)
  }, context_instance = RequestContext(request))

Example 11

Project: Observatory
Source File:
View license
def view_list(request,list_id=0,list_slug=None,view_completed=0):
    Display and manage items in a task list
    # Make sure the accessing user has permission to view this list.
    # Always authorize the "mine" view. Admins can view/edit all lists.

    if list_slug == "mine"  or list_slug == "recent-add" or list_slug == "recent-complete" :
        auth_ok =1
        list = get_object_or_404(List, slug=list_slug)
        listid =    
        # Check whether current user is a member of the group this list belongs to.
        if in request.user.groups.all() or request.user.mentor or list_slug == "mine" :
            auth_ok = 1   # User is authorized for this view
        else: # User does not belong to the group this list is attached to
            messages.error(request, "You do not have permission to view/edit this list.")                                    

    # First check for items in the mark_done POST array. If present, change
    # their status to complete.
    if request.POST.getlist('mark_done'):
        done_items = request.POST.getlist('mark_done')
        # Iterate through array of done items and update its representation in the model
        for thisitem in done_items:
            p = Item.objects.get(id=thisitem)
            p.completed = 1
            p.completed_date =
            messages.success(request, "Item \"%s\" marked complete." % p.title)                                             

    # Undo: Set completed items back to incomplete
    if request.POST.getlist('undo_completed_task'):
        undone_items = request.POST.getlist('undo_completed_task')
        for thisitem in undone_items:
            p = Item.objects.get(id=thisitem)
            p.completed = 0
            messages.success(request, "Previously completed task \"%s\" marked incomplete." % p.title)

    # And delete any requested items
    if request.POST.getlist('del_task'):
        deleted_items = request.POST.getlist('del_task')
        for thisitem in deleted_items:
            p = Item.objects.get(id=thisitem)
            messages.success(request, "Item \"%s\" deleted." % p.title)         

    # And delete any *already completed* items
    if request.POST.getlist('del_completed_task'):
        deleted_items = request.POST.getlist('del_completed_task')
        for thisitem in deleted_items:
            p = Item.objects.get(id=thisitem)
            messages.success(request, "Deleted previously completed item \"%s\"."  % p.title)                       

    thedate =
    created_date = "%s-%s-%s" % (thedate.year, thedate.month,

    # Get list of items with this list ID, or filter on items assigned to me, or recently added/completed
    if list_slug == "mine":
        task_list = Item.objects.filter(assigned_to=request.user, completed=0)
        completed_list = Item.objects.filter(assigned_to=request.user, completed=1)
    elif list_slug == "recent-add":
        # We'll assume this only includes uncompleted items to avoid confusion.
        # Only show items in lists that are in groups that the current user is also in.
        task_list = Item.objects.filter(list__group__in=(request.user.groups.all()),completed=0).order_by('-created_date')[:50]
        # completed_list = Item.objects.filter(assigned_to=request.user, completed=1)   
    elif list_slug == "recent-complete":
        # Only show items in lists that are in groups that the current user is also in.
        task_list = Item.objects.filter(list__group__in=request.user.groups.all(),completed=1).order_by('-completed_date')[:50]
        # completed_list = Item.objects.filter(assigned_to=request.user, completed=1)             

        task_list = Item.objects.filter(, completed=0)
        completed_list = Item.objects.filter(, completed=1)

    if request.POST.getlist('add_task') :
        form = AddItemForm(list, request.POST,initial={
        if form.is_valid():
            # Save task first so we have a db object to play with
            new_task =

            # Send email alert only if the Notify checkbox is checked AND the assignee is not the same as the submittor
            # Email subect and body format are handled by templates
            if "notify" in request.POST :
                if new_task.assigned_to != request.user :
                    # Send email
                    email_subject = render_to_string("todo/email/assigned_subject.txt", { 'task': new_task })                    
                    email_body = render_to_string("todo/email/assigned_body.txt", { 'task': new_task, 'site': current_site, })
                        send_mail(email_subject, email_body,, [], fail_silently=False)
                        messages.error(request, "Task saved but mail not sent. Contact your administrator.")

            messages.success(request, "New task \"%s\" has been added." % new_task.title)                       
            return HttpResponseRedirect(request.path)

        if list_slug != "mine" and list_slug != "recent-add" and list_slug != "recent-complete" : # We don't allow adding a task on the "mine" view
            form = AddItemForm(list, initial={
                } )

    if request.user.mentor :
        can_del = 1

    return render_to_response('todo/view_list.html', locals(), context_instance=RequestContext(request))

Example 12

Project: Resmin
Source File:
View license
def profile(request, username=None, listing='public', action=None):

    user = get_object_or_404(User, username=username, is_active=True) if \
        username else request.user

    user_is_blocked_me, user_is_blocked_by_me,\
        i_am_follower_of_user, have_pending_follow_request \
        = False, False, False, False

    if request.user.is_authenticated():
        user_is_blocked_me = user.is_blocked_by(request.user)
        user_is_blocked_by_me = user.is_blocked_by(request.user)
        i_am_follower_of_user = request.user.is_following(user)
        have_pending_follow_request = \

    ctx = {'profile_user': user,
           'listing': listing,
           'user_is_blocked_by_me': user_is_blocked_by_me,
           'user_is_blocked_me': user_is_blocked_me,
           'have_pending_follow_request': have_pending_follow_request,
           'i_am_follower_of_user': i_am_follower_of_user}

    # If there are not blocks, fill ctx with answers
    if not (user_is_blocked_me or user_is_blocked_by_me):
        stories =
            frm=user, requested_user=request.user, listing=listing)
        ctx['stories'] = paginated(request, stories,
    if request.POST:
        question_form = QuestionForm(request.POST, questioner=request.user,
        if question_form.is_valid():
            messages.success(request, _('Your question sent to user.'))
            return HttpResponseRedirect(user.get_absolute_url())
        question_form = QuestionForm(questioner=request.user,

    if action:
        ctx['action'] = action
        follow_form = FollowForm(follower=request.user,
        if request.POST:
            follow_form = FollowForm(request.POST,
            if follow_form.is_valid():
                if action == 'follow':
                        request, _('Follow request sent to user'))
                elif action == 'unfollow':
                        request, _('You are not a follower anymore'))
                elif action == 'block':
                        request, _('You have blocked this user'))
                elif action == 'unblock':
                        request, _('You have unblocked this user'))
                return HttpResponseRedirect(user.get_absolute_url())

        ctx['follow_form'] = follow_form
    ctx['question_form'] = question_form

    return render(request, "auth/user_detail.html", ctx)

Example 13

Project: reviewboard
Source File:
View license
    def process_diffset_info(self, diffset_or_id, filediff_id,
                             interfilediff_id=None, interdiffset_or_id=None,
        """Process and return information on the desired diff.

        The diff IDs and other data passed to the view can be processed and
        converted into DiffSets. A dictionary with the DiffSet and FileDiff
        information will be returned.

        A subclass may instead return a HttpResponse to indicate an error
        with the DiffSets.
        # Depending on whether we're invoked from a URL or from a wrapper
        # with precomputed diffsets, we may be working with either IDs or
        # actual objects. If they're objects, just use them as-is. Otherwise,
        # if they're IDs, we want to grab them both (if both are provided)
        # in one go, to save on an SQL query.
        diffset = None
        interdiffset = None

        diffset_ids = []

        if isinstance(diffset_or_id, DiffSet):
            diffset = diffset_or_id

        if interdiffset_or_id:
            if isinstance(interdiffset_or_id, DiffSet):
                interdiffset = interdiffset_or_id

        if diffset_ids:
            diffsets = DiffSet.objects.filter(pk__in=diffset_ids)

            if len(diffsets) != len(diffset_ids):
                raise Http404

            for temp_diffset in diffsets:
                if == diffset_or_id:
                    diffset = temp_diffset
                elif == interdiffset_or_id:
                    interdiffset = temp_diffset
                    assert False

        filediff = get_object_or_404(FileDiff, pk=filediff_id, diffset=diffset)

        if interfilediff_id:
            interfilediff = get_object_or_404(FileDiff, pk=interfilediff_id,
            interfilediff = None

        # Store this so we don't end up causing an SQL query later when looking
        # this up.
        filediff.diffset = diffset

        diff_file = self._get_requested_diff_file(diffset, filediff,
                                                  interdiffset, interfilediff)

        if not diff_file:
            raise UserVisibleError(
                _('Internal error. Unable to locate file record for '
                  'filediff %s')

        return {
            'diffset': diffset,
            'interdiffset': interdiffset,
            'filediff': filediff,
            'diff_file': diff_file,

Example 14

Project: wagtailplus
Source File:
View license
def confirm_page_reversion(request, revision_id, template_name='wagtailrollbacks/pages/confirm_reversion.html'):
    Handles page reversion process (GET and POST).

    :param request: the request instance.
    :param revision_id: the page revision ID.
    :param template_name: the template name.
    :rtype: django.http.HttpResponse.
    revision    = get_object_or_404(PageRevision, pk=revision_id)
    page        =

    if page.locked:
            _("Page '{0}' is locked.").format(page.title),
            buttons = []

        return redirect(reverse('wagtailadmin_pages:edit', args=(,)))

    page_perms = page.permissions_for_user(request.user)
    if not page_perms.can_edit():
        raise PermissionDenied

    if request.POST:
        is_publishing   = bool(request.POST.get('action-publish')) and page_perms.can_publish()
        is_submitting   = bool(request.POST.get('action-submit'))
        new_revision    = page.rollback(
            revision_id                 = revision_id,
            user                        = request.user,
            submitted_for_moderation    = is_submitting

        if is_publishing:

                _("Page '{0}' published.").format(page.title),
                    messages.button(page.url, _('View live')),
                    messages.button(reverse('wagtailadmin_pages:edit', args=(,)), _('Edit'))
        elif is_submitting:
                _("Page '{0}' submitted for moderation.").format(page.title),
                    messages.button(reverse('wagtailadmin_pages:view_draft', args=(,)), _('View draft')),
                    messages.button(reverse('wagtailadmin_pages:edit', args=(,)), _('Edit'))
            send_notification(, 'submitted',
                _("Page '{0}' updated.").format(page.title),

        for fn in hooks.get_hooks('after_edit_page'):
            result = fn(request, page)
            if hasattr(result, 'status_code'):
                return result

        return redirect('wagtailadmin_explore', page.get_parent().id)

    return render(
            'page':         page,
            'revision':     revision,
            'page_perms':   page_perms

Example 15

Source File:
View license
def edit(request, type, id):
    context = RequestContext(request)
    username = request.user.get_profile()       
    if type == 'opportunities':
        announcement = get_object_or_404(Opportunity, id=id, is_spam=False)
        announcement_form = OpportunityForm(
                                request.POST or None, 
                                request.FILES or None, 
    elif type == 'jobs':
        announcement = get_object_or_404(Job, id=id, is_spam=False)
        announcement_form = JobForm(
                                request.POST or None, 
                                request.FILES or None, 
    elif type == 'events':
        announcement = get_object_or_404(Event, id=id, is_spam=False)
        announcement_form = EventForm(
                                request.POST or None, 
                                request.FILES or None, 
        raise Http404
    if not announcement.can_edit():
        # can only edit if announcement less than 2 wks old...    
        return HttpResponseRedirect(reverse('announce_index'))  
        if request.user != announcement.user:
            return HttpResponseRedirect(reverse('announce_index'))  
            # HANDLE THE POST
            if request.method == 'POST':
                if request.POST.get("form-type") == "opportunity-form":
                    announcement_form = OpportunityForm(
                                            request.FILES or None, 
                if request.POST.get("form-type") == "job-form":
                    announcement_form = JobForm(
                                            request.FILES or None, 
                if request.POST.get("form-type") == "event-form":  
                    announcement_form = EventForm(
                                            request.FILES or None, 
                if announcement_form.is_valid():
                    announcement =
                    announcement.user_id =
                    announcement.ip_address = request.META["REMOTE_ADDR"]
                    if request.POST.get("delete_image"):
                        if announcement.image:
                            import os
                            if os.path.exists(announcement.image.path):
                        announcement.image = None
                    #save now so can create thumbanail with id in title
                    if announcement.image and not announcement.thumbnail:
                        announcement.thumbnail = create_thumbnail(announcement.image)
                    # if announcement is not yet published
                    if request.POST.get("status") == "preview":
                        announcement.status = False
                        return HttpResponseRedirect(reverse(preview, kwargs={'type':type, 'id'}))                    
                    if request.POST.get("status") == "publish":

                        if type == 'jobs' and not announcement.is_paid() and not request.user.get_profile().is_member():
                            return HttpResponseRedirect(reverse(job_payment))

                        if not moderator.process(announcement, request):
                            announcement.status = True
                            send_to_announce_mailing_list(announcement.__class__, announcement, created=True)
                        return HttpResponseRedirect(reverse(thanks, kwargs={'type':type,'id'}))

                    # if announcement is published
                    if request.POST.get("status") == "unpublish":
                        announcement.status = False
                        #return HttpResponseRedirect('/announce/%s/%s/preview/' % (type,
                        return HttpResponseRedirect(reverse(edit,kwargs={'type':type,'id'}))

                    if request.POST.get("status") == "update":
                        moderator.process(announcement, request)
                        #return HttpResponseRedirect('/announce/%s/%s/preview/' % (type,
                        return HttpResponseRedirect(reverse(thanks,kwargs={'type':type,'id'}))
                        if type == 'opportunities':   
                            announcement_form = OpportunityForm(request.POST)
                        if type == 'jobs':   
                            announcement_form = JobForm(request.POST)
                        if type == 'events':   
                            announcement_form = EventForm(request.POST)       
        return render_to_response(
            "type": type  

Example 16

Source File:
View license
def approval_voting_wrapper(request, object_id):
    stage 1 in commissions voting.
    allows members to go through proposals and decide if meet criteria.
    cycle = get_object_or_404(Cycle, pk=object_id)
    today =

    prev_votes = [a.proposal_id for a in ApprovalVote.objects \
                    .filter(user = request.user) \
                    .filter(created__gte = cycle.submission_start_date)]

    if today > cycle.approval_vote_start and today < cycle.approval_vote_end:
        current_proposal = None
        approval_status = None

        proposals = Proposal.objects \
            .filter(cycle=cycle) \
            .filter(submitted=True) \
            .filter(is_public=True) \
            .exclude(pk__in=prev_votes) \
            .exclude(deleted=True) \

        awaiting_length = len(proposals)
        paginator = Paginator(proposals, 1)

            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1

            awaiting_approval =
        except (EmptyPage, InvalidPage):
            awaiting_approval =

        if request.GET.get('proposal'):
            proposal_id = request.GET.get('proposal')
            proposal_id = proposal_id.replace('/', '')
            current_proposal = get_object_or_404(Proposal, id = proposal_id)
            for p in awaiting_approval.object_list:
                current_proposal = p

        #has user voted for this prop yet?
            approval_vote_for_prop = ApprovalVote.objects.get(user=request.user, proposal=current_proposal)
            if approval_vote_for_prop.approved:
                approval_status = 'approved'
            if not approval_vote_for_prop.approved:
                approval_status = 'not approved'
            approval_status = None

        if approval_status == 'approved':
            voting_form = ApprovalVoteForm(initial={
                'user': request.user,
                'proposal': current_proposal,
                'approved': True
        elif approval_status == 'not approved':
            voting_form = ApprovalVoteForm(initial={
                'user': request.user,
                'proposal': current_proposal,
                'approved': False,
            voting_form = ApprovalVoteForm(initial={'user':request.user, 'proposal':current_proposal})

        return render_to_response('commissions/approval_voting_wrapper.html', {
                'voting_form': voting_form,
                'awaiting_approval': awaiting_approval,
                'approval_status': approval_status,
                'current_proposal': current_proposal,
                'awaiting_length': awaiting_length,
        return HttpResponseRedirect(reverse('commissions_voting', args=[]))

Example 17

Project: rocket-league-replays
Source File:
View license
    def get_serializer_context(self):
        user = get_object_or_404(User, pk=self.kwargs['user_id'])
        context = user.profile.stream_settings
        context['user'] = user

        # Data
        context['games_played'] = user.replay_set.all()
        context['wins'] = 0
        context['losses'] = 0

        context['average_goals'] = 0
        context['average_assists'] = 0
        context['average_saves'] = 0
        context['average_shots'] = 0
        context['win_percentage'] = 0
        context['goal_assist_ratio'] = 0

        goal_data = []
        assist_data = []
        save_data = []
        shot_data = []

        if context['limit_to'] == '3':
            context['games_played'] = context['games_played'][:3]
        elif context['limit_to'] == '5':
            context['games_played'] = context['games_played'][:5]
        elif context['limit_to'] == '10':
            context['games_played'] = context['games_played'][:10]
        elif context['limit_to'] == '20':
            context['games_played'] = context['games_played'][:20]
        elif context['limit_to'] == 'hour':
            context['games_played'] = context['games_played'].filter(
                timestamp__gte=now() - datetime.timedelta(hours=1)
        elif context['limit_to'] == 'today':
            context['games_played'] = context['games_played'].filter(
                timestamp__gte=now() - datetime.timedelta(days=1)

        elif context['limit_to'] == 'week':
            context['games_played'] = context['games_played'].filter(
                timestamp__gte=now() - datetime.timedelta(days=7)
        elif context['limit_to'] == 'all':
            # We don't need to do anything here.
        # elif context['limit_to'] == 'session':
        #     pass

        # What team was the user on?
        uid = user.social_auth.get(provider='steam').uid

        for replay in context['games_played']:
            # Which team was this user on?
            player = replay.player_set.filter(
                platform__in=['OnlinePlatform_Steam', '1'],

            if player.count() == 0:

            player = player[0]

            if == 0:
                if replay.team_0_score > replay.team_1_score:
                    context['wins'] += 1
                    context['losses'] += 1
            elif == 1:
                if replay.team_1_score > replay.team_0_score:
                    context['wins'] += 1
                    context['losses'] += 1


        context['games_played'] = context['games_played'].count()

        # Avoid dividing by zero.
        if len(goal_data) > 0:
            context['average_goals'] = "{0:.2f}".format(sum(goal_data) / len(goal_data))

        if len(assist_data) > 0:
            context['average_assists'] = "{0:.2f}".format(sum(assist_data) / len(assist_data))

        if len(save_data) > 0:
            context['average_saves'] = "{0:.2f}".format(sum(save_data) / len(save_data))

        if len(shot_data) > 0:
            context['average_shots'] = "{0:.2f}".format(sum(shot_data) / len(shot_data))

        if context['games_played'] > 0:
            context['win_percentage'] = "{0:.2f}".format(context['wins'] / context['games_played'] * 100)

        if sum(assist_data) > 0:
            context['goal_assist_ratio'] = "{0:.2f}".format(sum(goal_data) / sum(assist_data))
            context['goal_assist_ratio'] = sum(goal_data)

        return context

Example 18

Source File:
View license
@decorators.renderer_classes((JSONRenderer, JSONPRenderer))
def footer_html(request):
    project_slug = request.GET.get('project', None)
    version_slug = request.GET.get('version', None)
    page_slug = request.GET.get('page', None)
    theme = request.GET.get('theme', False)
    docroot = request.GET.get('docroot', '')
    subproject = request.GET.get('subproject', False)
    source_suffix = request.GET.get('source_suffix', '.rst')

    new_theme = (theme == "sphinx_rtd_theme")
    using_theme = (theme == "default")
    project = get_object_or_404(Project, slug=project_slug)
    version = get_object_or_404(
        Version.objects.public(request.user, project=project, only_active=False),
    main_project = project.main_language_project or project

    if page_slug and page_slug != "index":
        if (
                main_project.documentation_type == "sphinx_htmldir" or
                main_project.documentation_type == "mkdocs"):
            path = page_slug + "/"
        elif main_project.documentation_type == "sphinx_singlehtml":
            path = "index.html#document-" + page_slug
            path = page_slug + ".html"
        path = ""

    if version.type == TAG and version.project.has_pdf(version.slug):
        print_url = (
        print_url = None

    version_compare_data = get_version_compare_data(project, version)

    context = {
        'project': project,
        'version': version,
        'path': path,
        'downloads': version.get_downloads(pretty=True),
        'current_version': version.verbose_name,
        'versions': project.ordered_active_versions(user=request.user),
        'main_project': main_project,
        'translations': main_project.translations.all(),
        'current_language': project.language,
        'using_theme': using_theme,
        'new_theme': new_theme,
        'settings': settings,
        'subproject': subproject,
        'print_url': print_url,
        'github_edit_url': version.get_github_url(docroot, page_slug, source_suffix, 'edit'),
        'github_view_url': version.get_github_url(docroot, page_slug, source_suffix, 'view'),
        'bitbucket_url': version.get_bitbucket_url(docroot, page_slug, source_suffix),

    request_context = RequestContext(request, context)
    html = template_loader.get_template('restapi/footer.html').render(request_context)
    resp_data = {
        'html': html,
        'version_compare': version_compare_data,
        'version_supported': version.supported,

    # Allow folks to hook onto the footer response for various information usage.
    footer_response.send(sender=None, request=request, context=context, resp_data=resp_data)

    return Response(resp_data)

Example 19

Project: satnogs-network
Source File:
View license
def station_view(request, id):
    """View for single station page."""
    station = get_object_or_404(Station, id=id)
    form = StationForm(instance=station)
    antennas = Antenna.objects.all()
    rigs = Rig.objects.all()

        satellites = Satellite.objects.filter(transmitters__alive=True).distinct()
        pass  # we won't have any next passes to display

    # Load the station information and invoke ephem so we can
    # calculate upcoming passes for the station
    observer = ephem.Observer()
    observer.lon = str(station.lng) = str(
    observer.elevation = station.alt

    nextpasses = []
    passid = 0

    for satellite in satellites: =

            sat_ephem = ephem.readtle(str(satellite.latest_tle.tle0),

            # Here we are going to iterate over each satellite to
            # find its appropriate passes within a given time constraint
            keep_digging = True
            while keep_digging:
                    tr, azr, tt, altt, ts, azs = observer.next_pass(sat_ephem)

                    if tr is None:

                    # bug in pyephem causes overhead sats to appear in the result
                    # mixing next-pass data with current pass data, resulting in
                    # satnogs/satnogs-network#199. As a workaround, pyephem does
                    # return set time for current pass while rise time for next
                    # pass so when this happens we want to toss the entry out
                    # not a break as this sat might have another valid pass
                    if ts < tr:

                    # using the angles module convert the sexagesimal degree into
                    # something more easily read by a human
                    elevation = format(math.degrees(altt), '.0f')
                    azimuth = format(math.degrees(azr), '.0f')
                    passid += 1

                    # show only if >= configured horizon and in next 6 hours
                    if tr < + timedelta(hours=6)):
                        if float(elevation) >= station.horizon:
                            sat_pass = {'passid': passid,
                                        'mytime': str(,
                                        'debug': observer.next_pass(sat_ephem),
                                        'name': str(,
                                        'id': str(,
                                        'norad_cat_id': str(satellite.norad_cat_id),
                                        'tr': tr,           # Rise time
                                        'azr': azimuth,     # Rise Azimuth
                                        'tt': tt,           # Max altitude time
                                        'altt': elevation,  # Max altitude
                                        'ts': ts,           # Set time
                                        'azs': azs}         # Set azimuth
               = ephem.Date(ts).datetime() + timedelta(minutes=1)
                        keep_digging = False
                except ValueError:
                    break  # there will be sats in our list that fall below horizon, skip
                except TypeError:
                    break  # if there happens to be a non-EarthSatellite object in the list
                except Exception:
        except (ValueError, AttributeError):
            pass  # TODO: if something does not have a proper TLE line we need to know/fix

    return render(request, 'base/station_view.html',
                  {'station': station, 'form': form, 'antennas': antennas,
                   'mapbox_id': settings.MAPBOX_MAP_ID,
                   'mapbox_token': settings.MAPBOX_TOKEN,
                   'nextpasses': sorted(nextpasses, key=itemgetter('tr')),
                   'rigs': rigs})

Example 20

View license
def upload_example(request, object_id):
    This view renders the Uploadify file upload form.
    example = get_object_or_404(Example, id=object_id)

    # Create an options dictionary and pass it to uploadify_s3.UploadifyS3()
    # to set Uploadify options. See
    # These options override any set in your project settings file.
    # Here we specify the name of our JavaScript onComplete event handler.
    # See /media/js/uploadify_event_handlers.js.

        'onComplete'    : 'uploadifyOnComplete',

    # The key_pattern set here will be sent to S3 as the 'key' form field
    # below. You can use it to set the key (e.g. name) of your uploaded objects. 
    key_pattern = 'example-%s/${filename}' % object_id
    # Create a post_data dictionary and pass it to uploadify_s3.UploadifyS3()
    # to set any desired S3 POST variables.
    # See:
    # 'key' is the only required field that is not automatically set by DUS3. It
    # may be set here in the view or by setting the AWS_DEFAULT_KEY_PATTERN in
    # your project settings.
    # Note: Some reports indicate that Flash/Uploadify has problems with HTTP 
    # responses with an empty body. To avoid this, set a success_action_status
    # of 201, which forces S3 to return an XML document.
        'key': key_pattern,
        'success_action_status': "201",

    # S3 uses conditions to validate the upload data. DUS3 automatically constructs
    # and includes conditions for most of the elements that will be sent to S3, but you 
    # need to pass in conditions for:
    #   - 'key', whose value changes at upload time. Note that the condition's value
    #     must correspond to the key pattern set above.
    #   - any extra elements set at upload time
    # See the DUS3 README for more information on the conditions mapping:

        'key': {'op': 'starts-with', 'value': 'example-%s/' % object_id},

    # Initialize UploadifyS3 and call get_options_json() to get the Uploadify
    # JSON payload. 
    uploadify_options = uploadify_s3.UploadifyS3(

    # Pass the Uploadify JSON payload to the file_upload template as extra_context.
    return direct_to_template(request, 'examples/example_file_upload.html', extra_context={ 'example': example, 'uploadify_options': uploadify_options })

Example 21

Project: seantis-questionnaire
Source File:
View license
def questionnaire(request, runcode=None, qs=None):
    Process submitted answers (if present) and redirect to next page

    If this is a POST request, parse the submitted data in order to store
    all the submitted answers.  Then return to the next questionset or
    return a completed response.

    If this isn't a POST request, redirect to the main page.

    We only commit on success, to maintain consistency.  We also specifically
    rollback if there were errors processing the answers for this questionset.
    if use_session:
        session_runcode = request.session.get('runcode', None)
        if session_runcode is not None:
            runcode = session_runcode

        session_qs = request.session.get('qs', None)
        if session_qs is not None:
            qs = session_qs

    # if runcode provided as query string, redirect to the proper page
    if not runcode:
        runcode = request.GET.get('runcode')
        if not runcode:
            return HttpResponseRedirect("/")
            if not use_session:
                args = [runcode, ]
                request.session['runcode'] = runcode
                args = []
            return HttpResponseRedirect(reverse("questionnaire", args=args))

    runinfo = get_runinfo(runcode)

    if not runinfo:
        return HttpResponseRedirect('/')

    # let the runinfo have a piggy back ride on the request
    # so we can easily use the runinfo in places like the question processor
    # without passing it around
    request.runinfo = runinfo

    if not qs:
        # Only change the language to the subjects choice for the initial
        # questionnaire page (may be a direct link from an email)
        if hasattr(request, 'session'):
            request.session['django_language'] = runinfo.subject.language

    if 'lang' in request.GET:
        return set_language(request, runinfo, request.path)

    # --------------------------------
    # --- Handle non-POST requests ---
    # --------------------------------

    if request.method != "POST":
        if qs is not None:
            qs = get_object_or_404(QuestionSet, sortid=qs, questionnaire=runinfo.questionset.questionnaire)
            if runinfo.random.startswith('test:'):
                pass # ok for testing
            elif qs.sortid > runinfo.questionset.sortid:
                # you may jump back, but not forwards
                return redirect_to_qs(runinfo, request)
            runinfo.questionset = qs
        # no questionset id in URL, so redirect to the correct URL
        if qs is None:
            return redirect_to_qs(runinfo, request)
        questionset_start.send(sender=None, runinfo=runinfo, questionset=qs)
        return show_questionnaire(request, runinfo)

    # -------------------------------------
    # --- Process POST with QuestionSet ---
    # -------------------------------------

    # if the submitted page is different to what runinfo says, update runinfo
    # XXX - do we really want this?
    qs = request.POST.get('questionset_id', qs)
        qsobj = QuestionSet.objects.filter(pk=qs)[0]
        if qsobj.questionnaire == runinfo.questionset.questionnaire:
            if runinfo.questionset != qsobj:
                runinfo.questionset = qsobj

    questionnaire = runinfo.questionset.questionnaire
    questionset = runinfo.questionset

    # to confirm that we have the correct answers
    expected = questionset.questions()

    items = request.POST.items()
    extra = {} # question_object => { "ANSWER" : "123", ... }

    # this will ensure that each question will be processed, even if we did not receive
    # any fields for it. Also works to ensure the user doesn't add extra fields in
    for x in expected:
        items.append( (u'question_%s_Trigger953' % x.number, None) )

    # generate the answer_dict for each question, and place in extra
    for item in items:
        key, value = item[0], item[1]
        if key.startswith('question_'):
            answer = key.split("_", 2)
            question = get_question(answer[1], questionnaire)
            if not question:
                logging.warn("Unknown question when processing: %s" % answer[1])
            extra[question] = ans = extra.get(question, {})
            if(len(answer) == 2):
                ans['ANSWER'] = value
            elif(len(answer) == 3):
                ans[answer[2]] = value
                logging.warn("Poorly formed form element name: %r" % answer)
            extra[question] = ans

    errors = {}
    for question, ans in extra.items():
        if not question_satisfies_checks(question, runinfo):
        if u"Trigger953" not in ans:
            logging.warn("User attempted to insert extra question (or it's a bug)")
            cd = question.getcheckdict()
            # requiredif is the new way
            depon = cd.get('requiredif',None) or cd.get('dependent',None)
            if depon:
                depparser = BooleanParser(dep_check, runinfo, extra)
                if not depparser.parse(depon):
                    # if check is not the same as answer, then we don't care
                    # about this question plus we should delete it from the DB
                    delete_answer(question, runinfo.subject, runinfo.runid)
                    if cd.get('store', False):
                        runinfo.set_cookie(question.number, None)
            add_answer(runinfo, question, ans)
            if cd.get('store', False):
                runinfo.set_cookie(question.number, ans['ANSWER'])
        except AnswerException, e:
            errors[question.number] = e
        except Exception:
            logging.exception("Unexpected Exception")

    if len(errors) > 0:
        res = show_questionnaire(request, runinfo, errors=errors)
        return res


    next =
    while next and not questionset_satisfies_checks(next, runinfo):
        next =
    runinfo.questionset = next
    if use_session:
        request.session['prev_runcode'] = runinfo.random

    if next is None: # we are finished
        return finish_questionnaire(request, runinfo, questionnaire)

    return redirect_to_qs(runinfo, request)

Example 22

Project: coursys
Source File:
View license
def edit_case_info(request, course_slug, case_slug, field):
    View function for all of the "edit this aspect of the case" steps.  Uses the STEP_* dictionaries to get relevant strings/classes.
    course = get_object_or_404(CourseOffering, slug=course_slug)
    case = get_object_or_404(DisciplineCaseBase, slug=case_slug, offering__slug=course_slug)
    case = case.subclass()

    # permisson checks
    roles = request.session['discipline-'+course_slug]
    if not case.can_edit(field):
        # once instructor finished, don't allow editing those fields
        return ForbiddenResponse(request, "letter has been sent: cannot edit this field")
    elif isinstance(case, DisciplineCaseInstr) and "INSTR" not in roles:
        # only instructor can edit those fields
        return ForbiddenResponse(request, "only the instructor can edit this field")
    elif isinstance(case, DisciplineCaseChair) and "DEPT" not in roles:
        # only discipline admins can edit chair fields
        return ForbiddenResponse(request, "only the Chair (or delegate) can edit this field")

    FormClass = STEP_FORM[field]
    if request.method == 'POST':
        form = FormClass(request.POST, instance=case)
        if form.is_valid():
            c =
            if field in PRE_LETTER_STEPS:
                # letter hasn't been reviewed if anything changes
                c.letter_review = False
                c.letter_sent = 'WAIT'
                c.penalty_implemented = False

            #LOG EVENT#
            l = LogEntry(userid=request.user.username,
                  description=("edit discipline case %s in %s: changed %s") % (c.slug, c.offering, STEP_DESC[field]),
            messages.add_message(request, messages.SUCCESS, "Updated " + STEP_DESC[field] + '.')
            # set identical value for group members as requested
            also_contact = []
            for postfield in request.POST:
                match = also_set_re.match(postfield)
                if not match or request.POST[postfield] != "on":
                field ='field')
                caseid ='caseid')
                cases = DisciplineCaseBase.objects.filter(id=caseid)
                if len(cases) != 1 or cases[0].group !=
                c0 = cases[0].subclass()
                if not c0.can_edit(field):
                    messages.add_message(request, messages.ERROR,
                        "Case for %s is finished: cannot update %s." % (, STEP_DESC[field]))

                if field=="contacted" and form.cleaned_data[field]=='MAIL':
                    # special case handled below
                    setattr(c0, field, form.cleaned_data[field])
                    if field in PRE_LETTER_STEPS:
                        c0.letter_review = False
                    messages.add_message(request, messages.SUCCESS,
                        "Also updated %s for %s." % (STEP_DESC[field],
            if hasattr(c, 'send_letter_now'):
                # send instructor's letter
                assert case.public_attachments_size() <= MAX_ATTACHMENTS # should be ensured by "review letter" step
                messages.add_message(request, messages.INFO, "Letter sent to student summarizing case.")

            if hasattr(c, 'send_contact_mail'):
                # send initial contact email
                messages.add_message(request, messages.INFO, "Email sent to student notifying of case.")
                for c0 in also_contact:
                    textkey = 'also-contact_email_text-' + str(
                    if textkey in request.POST and request.POST[textkey]=="on":
                        # only send the email if text was updated too
                        c0.contacted = form.cleaned_data['contacted']
                        c0.contact_email_text = form.cleaned_data['contact_email_text']
                        messages.add_message(request, messages.SUCCESS,
                            "Also updated %s for %s." % (STEP_DESC['contacted'],
                        messages.add_message(request, messages.INFO, "Also emailed %s." % (
                        # if not, give an error message.
                        messages.add_message(request, messages.ERROR,
                            mark_safe('Email not sent to %s since their "Contact Email Text" was not updated. You can <a href="%s">edit their contact info</a> if you wish.'
                            % (,
                                    kwargs={'field': 'contacted', 'course_slug': course_slug, 'case_slug': c0.slug}))))
            if isinstance(case, DisciplineCaseChair):
                return HttpResponseRedirect(reverse('discipline.views.show_chair', kwargs={'course_slug': course_slug, 'case_slug': case.slug}))
                return HttpResponseRedirect(reverse('', kwargs={'course_slug': course_slug, 'case_slug': case.slug}))
        form = FormClass(instance=case)
    templates = DisciplineTemplate.objects.filter(field__in=form.fields.keys())
    tempaltesJSON = json.dumps([t.JSON_data() for t in templates])
    groupmembersJSON = case.groupmembersJSON()
    hasRelAct = len(case.related_activities())>0
    context = {'course': course, 'case': case, 'form': form,
        'templatesJSON': mark_safe(tempaltesJSON), 'groupmembersJSON': mark_safe(groupmembersJSON), 'hasRelAct': hasRelAct}
    if field == 'letter_review':
        context['currentuser'] = _currentuser(request)
    return render_to_response("discipline/edit_"+field+".html", context, context_instance=RequestContext(request))

Example 23

Project: coursys
Source File:
View license
def submit(request, course_slug):
    person = get_object_or_404(Person,userid=request.user.username)
    course = get_object_or_404(CourseOffering, slug = course_slug)
    member = Member.objects.exclude(role='DROP').get(person=person, offering=course)
    name = request.POST.get('GroupName')
    if name:
        name = name[:30]
    #Check if group has a unique name
    if Group.objects.filter(name=name,courseoffering=course):
        error_info="A group named \"%s\" already exists" % (name)
        messages.add_message(request, messages.ERROR, error_info)
        return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
    #Check if the group name is empty, these two checks may need to be moved to forms later.
    if name == "":
        error_info = "Group name cannot be empty: please enter a group name."
        messages.add_message(request, messages.ERROR, error_info)
        return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))

        # find selected activities
        selected_act = []
        activities = Activity.objects.filter(offering=course, group=True, deleted=False)
        if not is_course_staff_by_slug(request, course_slug):
            activities = activities.exclude(status='INVI')

        for activity in activities:
            activityForm = ActivityForm(request.POST, prefix=activity.slug)
            if activityForm.is_valid() and activityForm.cleaned_data['selected'] == True:
        # no selected activities: fail.
        if not selected_act:
            messages.add_message(request, messages.ERROR, "Group not created: no activities selected.")
            return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
        #groupForSemesterForm = GroupForSemesterForm(request.POST)
        #if groupForSemesterForm.is_valid():
        #    groupForSemester = groupForSemesterForm.cleaned_data['selected']
        groupForSemester = False
        #validate database integrity before saving anything. 
        #If one student is in a group for an activity, he/she cannot be in another group for the same activity.
        if is_course_student_by_slug(request, course_slug):
            isStudentCreatedGroup = True
            studentList = []
        elif is_course_staff_by_slug(request, course_slug):
            isStudentCreatedGroup = False
            studentList = []
            students = Member.objects.select_related('person').filter(offering = course, role = 'STUD')
            for student in students:
                studentForm = StudentForm(request.POST, prefix = student.person.userid)
                if studentForm.is_valid() and studentForm.cleaned_data['selected'] == True:
        #Check if students has already in a group
        if _validateIntegrity(request,isStudentCreatedGroup, groupForSemester, course, studentList, selected_act) == False:
            return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
        #No selected members,group creating will fail.        
        if not studentList:
            messages.add_message(request, messages.ERROR, "Group not created: no members selected.")
            return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
        group = Group(name=name, manager=member, courseoffering=course, groupForSemester = groupForSemester)
        #LOG EVENT#
        l = LogEntry(userid=request.user.username,
        description="created a new group %s for %s." % (, course),
        related_object=group )

        if is_course_student_by_slug(request, course_slug):
            for activity in selected_act:
                groupMember = GroupMember(group=group, student=member, confirmed=True,
                #LOG EVENT#
                l = LogEntry(userid=request.user.username,
                description="automatically became a group member of %s for activity %s." % (, groupMember.activity),
                    related_object=groupMember )

            messages.add_message(request, messages.SUCCESS, 'Group Created')
            return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))

        elif is_course_staff_by_slug(request, course_slug):
            students = Member.objects.select_related('person').filter(offering = course, role = 'STUD')
            for student in students:
                studentForm = StudentForm(request.POST, prefix = student.person.userid)
                if studentForm.is_valid() and studentForm.cleaned_data['selected'] == True:
                    for activity in selected_act:
                        groupMember = GroupMember(group=group, student=student, confirmed=True,
                        #LOG EVENT#
                        l = LogEntry(userid=request.user.username,
                        description="added %s as a group member to %s for activity %s." % (student.person.userid,, groupMember.activity),
                            related_object=groupMember )
                    n = NewsItem(user=student.person, author=member.person, course=group.courseoffering,
                     source_app="group", title="Added to Group",
                     content="You have been added the group %s." % (,
                     url=reverse('groups.views.groupmanage', kwargs={'course_slug':course.slug})
            messages.add_message(request, messages.SUCCESS, 'Group Created')
            return HttpResponseRedirect(reverse('groups.views.view_group', kwargs={'course_slug': course_slug, 'group_slug': group.slug}))
            return HttpResponseForbidden()

Example 24

Project: coursys
Source File:
View license
def _edit_pagefile(request, course_slug, page_label, kind):
    View to create and edit pages
    if request.method == 'POST' and 'delete' in request.POST and request.POST['delete'] == 'yes':
        return _delete_pagefile(request, course_slug, page_label, kind)
    with django.db.transaction.atomic():
        offering = get_object_or_404(CourseOffering, slug=course_slug)
        if page_label:
            page = get_object_or_404(Page, offering=offering, label=page_label)
            version = page.current_version()
            member = _check_allowed(request, offering, page.can_write, page.editdate())
            old_label = page.label
            page = None
            version = None
            member = _check_allowed(request, offering, offering.page_creators()) # users who can create pages
            old_label = None

        if isinstance(member, PagePermission):
            return ForbiddenResponse(request, 'Editing of pages by additional-permission holders is not implemented. Sorry')

        # make sure we're looking at the right "kind" (page/file)
        if not kind:
            kind = "file" if version.is_filepage() else "page"

        # get the form class we need
        if kind == "page":
            Form = EditPageForm
            Form = EditFileForm
        # check that we have an allowed member of the course (and can continue)
        if not member:
            return ForbiddenResponse(request, 'Not allowed to edit/create this '+kind+'.')
        restricted = False
        if member.role == 'STUD':
            # students get the restricted version of the form
            Form = Form.restricted_form
            restricted = True
        if request.method == 'POST':
            form = Form(instance=page, offering=offering, data=request.POST, files=request.FILES)
            if form.is_valid():
                instance =
                # clean up weirdness from restricted form
                if 'label' not in form.cleaned_data:
                    # happens when student edits an existing page
                    instance.label = page.label
                if 'can_write' not in form.cleaned_data:
                    # happens only when students create a page
                    instance.can_write = 'STUD'
                if not restricted and 'releasedate' in form.cleaned_data:
                elif not restricted:

                if not restricted and 'editdate' in form.cleaned_data:
                elif not restricted:

                instance.redirect = None

                if old_label and old_label != instance.label:
                    # page has been moved to a new URL: leave a redirect in its place
                    redir_page = Page(offering=instance.offering, label=old_label,
                                      can_read=instance.can_read, can_write=offering.page_creators())
                    redir_version = PageVersion(page=redir_page, title=version.title, redirect=instance.label,
                                                editor=member, comment='automatically generated on label change')
          , 'Page label changed: the old location (%s) will redirect to this page.' % (old_label,))

                #LOG EVENT#
                l = LogEntry(userid=request.user.username,
                      description="Edited page %s in %s." % (instance.label, offering),
                if page:
                    messages.success(request, "Edited "+kind+" \"%s\"." % (instance.label))
                    messages.success(request, "Created "+kind+" \"%s\"." % (instance.label))

                if not page and instance.label == 'Index' and not offering.url():
                    # new Index page but no existing course URL: set as course web page
                    url = settings.BASE_ABS_URL + instance.get_absolute_url()
          , "Set course URL to new Index page.")
                return HttpResponseRedirect(reverse('pages.views.view_page', kwargs={'course_slug': course_slug, 'page_label': instance.label}))
            form = Form(instance=page, offering=offering)
            if 'label' in request.GET:
                label = request.GET['label']
                if label == 'Index':
                    form.initial['title'] =
                    form.fields['label'].help_text += u'\u2014the label "Index" indicates the front page for this course.'
                elif label == MACRO_LABEL:
                    form.initial['can_read'] = 'INST'
                    form.initial['can_write'] = 'INST'
                    form.initial['title'] = MACRO_LABEL
                    form.initial['title'] = label.title()
                form.initial['label'] = label

        context = {
            'offering': offering,
            'page': page,
            'form': form,
            'kind': kind.title(),
            'is_macro_page': form.initial.get('title', None) == MACRO_LABEL,
        return render(request, 'pages/edit_page.html', context)

Example 25

Project: coursys
Source File:
View license
def _show_components_student(request, course_slug, activity_slug, userid=None, template="dashboard_student.html", staff=False):
    Show all the component submission history of this activity
    if userid == None:
        userid = request.user.username
    course = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(course.activity_set,slug=activity_slug, deleted=False)
    student = get_object_or_404(Person, find_userid_or_emplid(userid))
    cansubmit = True
    submission_configured = SubmissionComponent.objects.filter(
    if not submission_configured:
        return NotFoundResponse(request)

    submission_info = SubmissionInfo(student=student, activity=activity)
    if activity.multisubmit():

    any_submissions = bool(submission_info.submissions)

    if submission_info.submissions and activity.due_date and activity.due_date < submission_info.latest().created_at:
        late = submission_info.latest().created_at - activity.due_date
        late = 0
        gm = GroupMember.objects.filter(student__person=student, activity=activity, confirmed=True)
        if gm:
            group = gm[0].group
            member = gm[0].student
            group = None

        group = None

    # activity should be submitable
    cansubmit = cansubmit and activity.submitable()

    if not cansubmit:
        messages.add_message(request, messages.ERROR, "This activity is not submittable.")
        return render(request, "submission/" + template,
        {"course":course, "activity":activity, "submission_info": submission_info, 'any_submissions': any_submissions,
         "userid":userid, "late":late, "student":student, "group":group, "cansubmit":cansubmit})

    # get all components of activity
    component_list = select_all_components(activity)

    if request.method == 'POST':
        component_form_list = make_form_from_list(component_list, request=request)
        submitted_comp = []    # list all components which has content submitted in the POST
        not_submitted_comp = [] #list allcomponents which has no content submitted in the POST
        if not
            new_sub = StudentSubmission()   # the submission foreign key for newly submitted components
            new_sub.member = get_object_or_404(Member, offering__slug=course_slug, person__userid=request.user.username)
        elif gm:
            new_sub = GroupSubmission()
   = group
            new_sub.creator = member
            messages.add_message(request, messages.ERROR, "This is a group submission. You cannot submit since you aren't in a group.")
            return ForbiddenResponse(request)
        new_sub.activity = activity

        # begin validating uploaded data
        submitted_comp = []
        not_submitted_comp = []
        # validate forms one by one
        for data in component_form_list:
            component = data['comp']
            form = data['form']
            if form.is_valid():
                sub =
                sub.component = component
                # hack to replace the "required" message to something more appropriate
                for k,v in form.errors.items():
                    for i,e in enumerate(v):
                        if e == "This field is required.":
                            v[i] = "Nothing submitted."

        # check duplicate filenames here
        all_ok = False
        while not all_ok:
            all_ok = True
            d = {}
            if not activity.multisubmit():
                # single-submit logic: don't want to overrite filenames from earlier submissions that are still in-play
                for c,s in submission_info.components_and_submitted():
                    d[c] = s and s.get_filename()
            # filenames from this submission
            for s in submitted_comp:
                d[s.component] = s.get_filename()
            # a list holding all file names
            file_name_list = [a[1] for a in d.items() if a[1] is not None]
            to_be_removed = []
            for (i, s) in enumerate(submitted_comp):
                if file_name_list.count(s.get_filename()) > 1:
                    all_ok = False
                    #HACK: modify the 'errors' field in the form
                    for data in component_form_list:
                        if s.component == data['comp']:
                            # assume we have only one field for submission form
                            field_name = data['form'].fields.keys()[0]
                            data['form']._errors[field_name] = ErrorList([u"This file has the same name as another file in your submission."])
            # remove those has errors in submitted_comp
            for t in to_be_removed:
        # all okay now
        # end validating, begin saving
        if len(submitted_comp) > 0:
        for sub in submitted_comp:
            sub.submission = new_sub
            #LOG EVENT#
                group_str = " as a member of group %s" %
                group_str = ""
            l = LogEntry(userid=request.user.username,
                  description=u"submitted for %s %s%s" % (activity, sub.component.title, group_str),

        if len(not_submitted_comp) == 0:
            messages.add_message(request, messages.SUCCESS, "Your submission was successful.")
            return HttpResponseRedirect(reverse(show_components, args=[course_slug, activity_slug]))

        return render(request, "submission/submission_error.html",
            {"course":course, "activity":activity, "component_list":component_form_list,
            "submitted_comp":submitted_comp, "not_submitted_comp":not_submitted_comp})
    else: #not POST
        component_form_list = make_form_from_list(component_list)
        return render(request, "submission/" + template,
        {'component_form_list': component_form_list, "course": course, "activity": activity, "submission_info": submission_info,
         "userid":userid, "late":late, "student":student, "group":group,
         "cansubmit":cansubmit, "is_staff":staff, 'any_submissions': any_submissions})

Example 26

Project: coursys
Source File:
View license
@requires_role(["TAAD", "GRAD"])
def contracts_csv(request, unit_slug, semester):
    hiring_semester = get_object_or_404(HiringSemester, 

    contracts = TAContract.objects.signed(hiring_semester)

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'inline; filename="%s.csv"' % (
    writer = csv.writer(response)
    writer.writerow(['Batch ID', 'Term ID', 'Contract Signed', 
                     'Benefits Indicator', 'EmplID', 'SIN',
                     'Last Name', 'First Name 1', 'First Name 2', 
                     'Payroll Start Date', 'Payroll End Date',
                     'Action', 'Action Reason', 'Position Number', 
                     'Job Code', 'Full_Part time', 'Pay Group',
                     'Employee Class', 'Category', 'Fund', 
                     'Dept ID (cost center)', 'Project', 'Account',
                     'Prep Units', 'Base Units', 'Appt Comp Freq', 
                     'Semester Base Salary Rate',
                     'Biweekly Base Salary Pay Rate', 
                     'Hourly Rate', 'Standard Hours', 'Scholarship Rate Code',
                     'Semester Scholarship Salary Pay Rate', 
                     'Biweekly Scholarship Salary Pay Rate', 'Lump Sum Amount',
                     'Lump Sum Hours', 'Scholarship Lump Sum', 'Course(s)'])
    seq = hiring_semester.next_export_seq()
    batchid = '%s_%s_%02i' % (hiring_semester.unit.label, 
                    "%Y%m%d"), seq)

    for c in contracts:
        bu = c.bu
        total_bu = c.total_bu
        prep_units = c.total_bu - c.bu
        signed = 'Y'
        benefits = 'Y'
        schol_rate = 'TSCH' if c.scholarship_per_bu > 0 else ''
        salary_total = c.total_pay 
        schol_total = c.scholarship_pay
        if prep_units == 0:
            prep_units = ''

        # Build a string of all course offerings tied to this contract to add to the results.
        course_list_string = ', '.join([unicode.encode( for ta_course in c.course.all()])
        row = []
        #Batch ID
        #Term ID
        #Benefits Indicator
        #Payroll Start Date, Payroll End Date
        #Action, Action Reason
        #Position Number
        row.append("%08i" % c.category.account.position_number)
        #Job Code
        #Full_Part time
        #Pay Group
        #Employee Class
        #Dept ID(cost center)
        #Prep Units
        #Base Units
        #Appt Comp Freq
        #Semester Base Salary Rate
        #Biweekly Base Salary Rate, Hourly Rate, Standard Hours
        #Scholarhip Rate Code
        #Semester Scholarship Salary Pay Rate
        #Biweekly Scholarship Salary Pay Rate, Lump Sum Amount
        #Lump Sum Hours, Scholarship Lump Sum
        # Course(s)

    return response

Example 27

Project: django-todo
Source File:
View license
def view_list(request, list_id=0, list_slug=None, view_completed=False):
    Display and manage items in a list.

    # Make sure the accessing user has permission to view this list.
    # Always authorize the "mine" view. Admins can view/edit all lists.
    if list_slug == "mine" or list_slug == "recent-add" or list_slug == "recent-complete":
        auth_ok = True
        list = get_object_or_404(List, id=list_id)
        if in request.user.groups.all() or request.user.is_staff or list_slug == "mine":
            auth_ok = True
        else:  # User does not belong to the group this list is attached to
            messages.error(request, "You do not have permission to view/edit this list.")

    # Process all possible list interactions on each submit
    mark_done(request, request.POST.getlist('mark_done'))
    del_tasks(request, request.POST.getlist('del_tasks'))
    undo_completed_task(request, request.POST.getlist('undo_completed_task'))

    thedate =
    created_date = "%s-%s-%s" % (thedate.year, thedate.month,

    # Get set of items with this list ID, or filter on items assigned to me, or recently added/completed
    if list_slug == "mine":
        task_list = Item.objects.filter(assigned_to=request.user, completed=False)
        completed_list = Item.objects.filter(assigned_to=request.user, completed=True)

    elif list_slug == "recent-add":
        # Only show items in lists that are in groups that the current user is also in.
        # Assume this only includes uncompleted items.
        task_list = Item.objects.filter(

    elif list_slug == "recent-complete":
        # Only show items in lists that are in groups that the current user is also in.
        task_list = Item.objects.filter(

        task_list = Item.objects.filter(, completed=0)
        completed_list = Item.objects.filter(, completed=1)

    if request.POST.getlist('add_task'):
        form = AddItemForm(list, request.POST, initial={
            'priority': 999,

        if form.is_valid():
            new_task =

            # Send email alert only if Notify checkbox is checked AND assignee is not same as the submitter
            if "notify" in request.POST and new_task.assigned_to != request.user:
                send_notify_mail(request, new_task)

            messages.success(request, "New task \"{t}\" has been added.".format(t=new_task.title))
            return HttpResponseRedirect(request.path)
        # Don't allow adding new tasks on some views
        if list_slug != "mine" and list_slug != "recent-add" and list_slug != "recent-complete":
            form = AddItemForm(list, initial={
                'priority': 999,

    return render(request, 'todo/view_list.html', locals())

Example 28

Project: baruwa
Source File:
View license
def detail(request, message_id, archive=False):
    Displays details of a message, and processes quarantined messages
    if archive:
        obj = Archive
        obj = Message
    message_details = get_object_or_404(obj, id=message_id)
    if not message_details.can_access(request):
        return HttpResponseForbidden(_('You are not authorized'
        ' to access this page'))

    delivery_reports = DeliveryInfo.objects.filter(id=message_id)
    error_list = ''
    quarantine_form = QuarantineProcessForm()
    'message_id'].widget.attrs['value'] =

    if request.method == 'POST':
        quarantine_form = QuarantineProcessForm(request.POST)
        if quarantine_form.is_valid():
            form_data = quarantine_form.cleaned_data
            form_data['message_id'] = [form_data['message_id']]
            task = ProcessQuarantine.apply_async(args=[form_data],
            html = []
            result = task.result[0]
            if task.status == 'SUCCESS':
                success = True
                if form_data['release']:
                    if form_data['use_alt']:
                        to_addr = form_data['altrecipients']
                        to_addr = message_details.to_address
                    to_addr = to_addr.split(',')
                    error_msg = ''
                    if not result['release']:
                        success = False
                        error_msg = dict(result['errors'])['release']
                    template = 'messages/released.html'
                        {'id':, 'addrs': to_addr,
                        'success': success, 'error_msg': error_msg}))
                if form_data['learn']:
                    error_msg = ''
                    template = "messages/salearn.html"
                    if not result['learn']:
                        success = False
                        error_msg = dict(result['errors'])['learn']
                        {'id':, 'msg': error_msg,
                        'success': success}))
                if form_data['todelete']:
                    error_msg = ''
                    if not result['delete']:
                        success = False
                        error_msg = dict(result['errors'])['delete']
                    template = "messages/delete.html"
                    {'id':, 'success': success,
                    'error_msg': error_msg}))
                html = '<br />'.join(html)
                success = False
                html = _('Processing the request failed')
            error_list = quarantine_form.errors.values()[0]
            error_list = error_list[0]
            html = error_list
            success = False
        if request.is_ajax():
            response = anyjson.dumps({'success': success, 'html': html})
            return HttpResponse(response,
            content_type='application/javascript; charset=utf-8')

    quarantine_form.fields['altrecipients'].widget.attrs['size'] = '55'
    return render_to_response('messages/detail.html', locals(),

Example 29

Project: shuup
Source File:
View license
def handle_add(request, basket, product_id, quantity=1, supplier_id=None, **kwargs):  # noqa (C901)
    Handle adding a product to the basket.

    :param product_id: product ID to add (or if `child_product_id` is truey, the parent ID)
    :param quantity: quantity of products to add
    :param child_product_id: child product ID to add (if truey)
    :param supplier_id: The supplier ID for the new line. If None, the first supplier is used.
    product_id = int(product_id)

    product = get_object_or_404(Product, pk=product_id)
    shop_product = product.get_shop_instance(
    if not shop_product:
        raise ValidationError("Product not available in this shop", code="product_not_available_in_shop")

    if supplier_id:
        supplier = shop_product.suppliers.filter(pk=supplier_id).first()
        supplier = shop_product.suppliers.first()

    if not supplier:
        raise ValidationError("Invalid supplier", code="invalid_supplier")

        quantity = parse_decimal_string(quantity)
        if not product.sales_unit.allow_fractions:
            if quantity % 1 != 0:
                msg = _(
                    "The quantity %f is not allowed. "
                    "Please use an integer value.") % quantity
                raise ValidationError(msg, code="invalid_quantity")
            quantity = int(quantity)
    except (ValueError, decimal.InvalidOperation):
        raise ValidationError(_(u"The quantity %s is not valid.") % quantity, code="invalid_quantity")

    if quantity <= 0:
        raise ValidationError(_(u"The quantity %s is not valid.") % quantity, code="invalid_quantity")

    product_ids_and_quantities = basket.get_product_ids_and_quantities()
    already_in_basket_qty = product_ids_and_quantities.get(, 0)
        quantity=(already_in_basket_qty + quantity),

    # If the product is a package parent, also check child products
    if product.is_package_parent():
        for child_product, child_quantity in six.iteritems(product.get_package_child_to_quantity_map()):
            already_in_basket_qty = product_ids_and_quantities.get(, 0)
            total_child_quantity = (quantity * child_quantity)
            sp = child_product.get_shop_instance(
                quantity=(already_in_basket_qty + total_child_quantity),

    # TODO: Hook/extension point
    # if product.form:
    #     return {
    #         "error": u"Form required",
    #         "return": reverse_GET("product-form", kwargs={"pk":}, GET={"n": quantity})
    #     }

    add_product_kwargs = {
        "product": product,
        "quantity": quantity,
        "supplier": supplier,


    return {
        'ok': basket.product_count,
        'added': quantity

Example 30

Project: oioioi
Source File:
View license
def model_solutions_view(request, problem_instance_id):
    problem_instance = \
        get_object_or_404(ProblemInstance, id=problem_instance_id)
    if not can_admin_problem_instance(request, problem_instance):
        raise PermissionDenied

    filter_kwargs = {
        'test__isnull': False,
                '__modelprogramsubmission__isnull': False,
        'submission_report__status': 'ACTIVE',
    test_reports = TestReport.objects.filter(**filter_kwargs) \
    filter_kwargs = {
                '__modelprogramsubmission__isnull': False,
        'submission_report__status': 'ACTIVE',
    group_reports = GroupReport.objects.filter(**filter_kwargs) \
    submissions = ModelProgramSubmission.objects \
            .filter(problem_instance=problem_instance) \
            .order_by('model_solution__order_key') \
            .select_related('model_solution') \
    tests = problem_instance.test_set \
            .order_by('order', 'group', 'name').all()

    group_results = defaultdict(lambda: defaultdict(lambda: None))
    for gr in group_reports:
        group_results[][gr.submission_report.submission_id] = gr

    test_results = defaultdict(lambda: defaultdict(lambda: None))
    for tr in test_reports:
        test_results[tr.test_id][tr.submission_report.submission_id] = tr

    submissions_percentage_statuses = { '25' for s in submissions}
    rows = []
    submissions_row = []
    for t in tests:
        row_test_results = test_results[]
        row_group_results = group_results[]
        percentage_statuses = { '100' for s in submissions}
        for s in submissions:
            if row_test_results[] is not None:
                time_ratio = float(row_test_results[].time_used) / \
                if time_ratio <= 0.25:
                    percentage_statuses[] = '25'
                elif time_ratio <= 0.50:
                    percentage_statuses[] = '50'
                    if submissions_percentage_statuses[] is not '100':
                        submissions_percentage_statuses[] = '50'
                    percentage_statuses[] = '100'
                    submissions_percentage_statuses[] = '100'

            'test': t,
            'results': [{
                    'test_report': row_test_results[],
                    'group_report': row_group_results[],
                    'is_partial_score': s.problem_instance.controller
                    'percentage_status': percentage_statuses[]
                for s in submissions

    for s in submissions:
        status = s.status
        if s.status == 'OK' or s.status == 'INI_OK':
            status = 'OK' + submissions_percentage_statuses[]

            'submission': s,
            'status': status

    total_row = {
        'test': sum(t.time_limit for t in tests),
            [sum(t[].time_used if t[] else 0
                 for t in test_results.values())
             for s in submissions],

    context = {
            'problem_instance': problem_instance,
            'submissions_row': submissions_row,
            'submissions': submissions,
            'rows': rows,
            'total_row': total_row

    return TemplateResponse(request, 'programs/admin/model_solutions.html',

Example 31

Project: oioioi
Source File:
View license
def get_round_context(request, round_pk):
    selected_round = get_object_or_404(Round, pk=round_pk)

    round = {}

    round['round'] = selected_round
    round['problem_instances'] = []

    problem_instances = {}

    controller = request.contest.controller
    queryset = ProblemInstance.objects.filter(round=selected_round) \

    visible_problem_instances = [pi for pi in queryset if
                                 controller.can_see_problem(request, pi)]

    for pi in visible_problem_instances:
        problem_instances[] = {}
        problem_instances[]['problem_instance'] = pi
        problem_instances[]['submission_count'] = 0
        problem_instances[]['question_count'] = 0
        problem_instances[]['solved_count'] = 0
        problem_instances[]['tried_solving_count'] = 0
        problem_instances[]['users_with_score'] = defaultdict(int)
        problem_instances[]['max_score'] = 0

    end_date = request.timestamp
    start_date = end_date - timedelta(days=RECENT_ACTIVITY_DAYS)

    last_week = [start_date, end_date]

    questions = Message.objects.filter(
        round=selected_round, date__range=last_week)

    for question in questions:
        if question.problem_instance is not None:
            problem_instance = problem_instances[]
            problem_instance['question_count'] += 1

    submissions = Submission.objects.filter(
        problem_instance__round=selected_round, date__range=last_week)

    for submission in submissions:
        problem_instance = problem_instances[]
        problem_instance['submission_count'] += 1

    results = UserResultForProblem.objects.filter(

    for result in results:
        problem_instance = problem_instances[]
        score_report = result.submission_report.score_report

        if score_report_is_valid(score_report):
            problem_instance['max_score'] = score_report.max_score.to_int()

            problem_instance['tried_solving_count'] += 1
            if score_report.score == score_report.max_score:
                problem_instance['solved_count'] += 1

                score_report.score.to_int()] += 1

    contest_data = {}

    for _, pi in problem_instances.items():
        scores = []

        for score, users_with_score in pi['users_with_score'].iteritems():
            scores.append([score, users_with_score])

        if pi['tried_solving_count'] == 0:
            pi['solved'] = 'none'
            solved_ratio = float(pi['solved_count']) \
                           / pi['tried_solving_count']

            if solved_ratio < 1. / 3:
                pi['solved'] = 'low'
            elif solved_ratio < 2. / 3:
                pi['solved'] = 'medium'
                pi['solved'] = 'high'

        pi['users_with_score'] = scores

        contest_data[pi['problem_instance'].short_name] = {
            'scores': scores,
            'max_score': pi['max_score']


    return {
        'selected_round': round,
        'contest_data': json.dumps(contest_data),

Example 32

Project: oioioi
Source File:
View license
@enforce_condition(contest_exists & is_teachers_contest & is_contest_admin)
def problem_settings(request, problem_instance_id):
    # Database objects.
    pi = get_object_or_404(ProblemInstance, id=problem_instance_id,
    p = pi.problem
    tags = p.tag_set.all()
    attachments = p.attachments.all()
    tests = pi.test_set.all()
    # Formsets
    TestFormset = modelformset_factory(Test, form=TestForm, extra=0)
    PIFormset = modelformset_factory(ProblemInstance,
                                     form=ProblemInstanceForm, extra=0)

    AttachmentFormset = inlineformset_factory(Problem, ProblemAttachment,
                                              extra=0, form=AttachmentForm,

    TagFormset = modelformset_factory(Tag, form=TagForm, extra=0,

    if request.method == 'POST':
        pif = PIFormset(request.POST, prefix='pif')

        test_formset = TestFormset(request.POST)
        # Bind the clean method, which serves as a time limit validator.
        test_formset.get_time_limit_sum = types.MethodType(
                TimeLimitFormset.__dict__['get_time_limit_sum'], test_formset)
        test_formset.validate_time_limit_sum = types.MethodType(
        test_formset.clean = types.MethodType(
                TimeLimitFormset.__dict__['clean'], test_formset)

        attachment_formset = \
            AttachmentFormset(request.POST, request.FILES, instance=p,
        tag_formset = TagFormset(request.POST, prefix='tag', queryset=tags)

        if pif.is_valid() and test_formset.is_valid() and \
                attachment_formset.is_valid() and tag_formset.is_valid():

            # Commit is set to False because of errors while deleting.
            instances =
            for inst in instances:
            for inst in attachment_formset.deleted_objects:

            # Commit is set to false because we don't want to persist
            # every Tag - we'll be persisting TagThrough instead.
            instances =
            for inst in instances:
                tag, _ = Tag.objects.get_or_create(name=inst)
                tt = TagThrough()
                tt.problem = p
                tt.tag = tag
            for inst in tag_formset.deleted_objects:
                TagThrough.objects.filter(tag=inst, problem=p).delete()

            return redirect(reverse('problem_settings', kwargs={
                'problem_instance_id': problem_instance_id}))

        test_forms = test_formset
        pi_form = pif

        test_forms = TestFormset(queryset=tests)
        pi_form = PIFormset(queryset=ProblemInstance.objects.filter(,
        attachment_formset = AttachmentFormset(queryset=attachments,
        tag_formset = TagFormset(prefix='tag', queryset=tags)

    context = {
        'problem_instance': pi,
        'problem': p,
        'tags': tags,
        'attachments': attachments,
        'tests': tests,
        'pi_form': pi_form,
        'test_forms': test_forms,

    for attachment_form in attachment_formset.forms:
    context['attachment_formset'] = attachment_formset
    context['tag_formset'] = tag_formset

    return TemplateResponse(request,
                            'simpleui/problem_settings/settings.html', context)

Example 33

Project: djangobb
Source File:
View license
def show_topic(request, topic_id, full=True):
    * Display a topic
    * save a reply
    * save a poll vote

    TODO: Add reply in lofi mode
    post_request = request.method == "POST"
    user_is_authenticated = request.user.is_authenticated()
    if post_request and not user_is_authenticated:
        # Info: only user that are logged in should get forms in the page.
        raise PermissionDenied

    topic = get_object_or_404(Topic.objects.select_related(), pk=topic_id)
    if not
        raise PermissionDenied
    Topic.objects.filter('views') + 1)

    last_post = topic.last_post

    if request.user.is_authenticated():
    posts = topic.posts.all().select_related()

    moderator = request.user.is_superuser or request.user in
    if user_is_authenticated and request.user in topic.subscribers.all():
        subscribed = True
        subscribed = False

    # reply form
    reply_form = None
    form_url = None
    back_url = None
    if user_is_authenticated and not topic.closed:
        form_url = request.path + "#reply" # if form validation failed: browser should scroll down to reply form ;)
        back_url = request.path
        ip = request.META.get('REMOTE_ADDR', None)
        post_form_kwargs = {"topic":topic, "user":request.user, "ip":ip}
        if post_request and AddPostForm.FORM_NAME in request.POST:
            reply_form = AddPostForm(request.POST, request.FILES, **post_form_kwargs)
            if reply_form.is_valid():
                post =
                messages.success(request, _("Your reply saved."))
                return HttpResponseRedirect(post.get_absolute_url())
            reply_form = AddPostForm(
                    'markup': request.user.forum_profile.markup,
                    'subscribe': request.user.forum_profile.auto_subscribe,

    # handle poll, if exists
    poll_form = None
    polls = topic.poll_set.all()
    if not polls:
        poll = None
        poll = polls[0]
        if user_is_authenticated: # Only logged in users can vote
            has_voted = request.user in poll.users.all()
            if not post_request or not VotePollForm.FORM_NAME in request.POST:
                # It's not a POST request or: The reply form was send and not a poll vote
                if and not has_voted:
                    poll_form = VotePollForm(poll)
                if not
                    messages.error(request, _("This poll is not active!"))
                    return HttpResponseRedirect(topic.get_absolute_url())
                elif has_voted:
                    messages.error(request, _("You have already vote to this poll in the past!"))
                    return HttpResponseRedirect(topic.get_absolute_url())

                poll_form = VotePollForm(poll, request.POST)
                if poll_form.is_valid():
                    ids = poll_form.cleaned_data["choice"]
                    queryset = poll.choices.filter(id__in=ids)
                    queryset.update(votes=F('votes') + 1)
                    poll.users.add(request.user) # save that this user has vote
                    messages.success(request, _("Your votes are saved."))
                    return HttpResponseRedirect(topic.get_absolute_url())

    highlight_word = request.GET.get('hl', '')
    view_data = {
        'categories': Category.objects.all(),
        'topic': topic,
        'posts_page': get_page(posts, request, forum_settings.TOPIC_PAGE_SIZE),
        'poll': poll,
        'poll_form': poll_form,
    if full:
            'last_post': last_post,
            'form_url': form_url,
            'reply_form': reply_form,
            'back_url': back_url,
            'moderator': moderator,
            'subscribed': subscribed,
            'highlight_word': highlight_word,
        return render(request, 'djangobb_forum/topic.html', view_data)
        return render(request, 'djangobb_forum/lofi/topic.html', view_data)

Example 34

Project: froide
Source File:
View license
def list_requests(request, status=None, topic=None, tag=None,
        jurisdiction=None, public_body=None, not_foi=False, feed=None):
    context = {
        'filtered': True
    manager = FoiRequest.published
    if not_foi:
        manager = FoiRequest.published_not_foi
    topic_list = PublicBodyTag.objects.get_topic_list()
    if status is None:
        status = request.GET.get(str(_('status')), None)
    status_url = status
    foi_requests = manager.for_list_view()
    if status is not None:
        func_status = FoiRequest.get_status_from_url(status)
        if func_status is None:
            raise Http404
        func, status = func_status
        foi_requests = foi_requests.filter(func(status))
            'status': FoiRequest.get_readable_status(status),
            'status_description': FoiRequest.get_status_description(status)
    elif topic is not None:
        topic = get_object_or_404(PublicBodyTag, slug=topic)
        foi_requests = manager.for_list_view().filter(public_body__tags=topic)
            'topic': topic,
    elif tag is not None:
        tag = get_object_or_404(Tag, slug=tag)
        foi_requests = manager.for_list_view().filter(tags=tag)
            'tag': tag
        foi_requests = manager.for_list_view()
        context['filtered'] = False

    if jurisdiction is not None:
        jurisdiction = get_object_or_404(Jurisdiction, slug=jurisdiction)
        foi_requests = foi_requests.filter(jurisdiction=jurisdiction)
            'jurisdiction': jurisdiction
    elif public_body is not None:
        public_body = get_object_or_404(PublicBody, slug=public_body)
        foi_requests = foi_requests.filter(public_body=public_body)
            'public_body': public_body
        context['filtered'] = True
        context['jurisdiction_list'] = Jurisdiction.objects.get_visible()
        context['jurisdiction_list'] = Jurisdiction.objects.get_visible()
        context['filtered'] = False

    if feed is not None:
        if feed == 'rss':
            klass = LatestFoiRequestsFeed
            klass = LatestFoiRequestsFeedAtom
        return klass(foi_requests, status=status_url, topic=topic,
            tag=tag, jurisdiction=jurisdiction)(request)

    count = foi_requests.count()

    page = request.GET.get('page')
    paginator = Paginator(foi_requests, 20)

    if request.GET.get('all') is not None:
        if count <= 500:
            paginator = Paginator(foi_requests, count)
        foi_requests =
    except PageNotAnInteger:
        foi_requests =
    except EmptyPage:
        foi_requests =

        'page_title': _("FoI Requests"),
        'count': count,
        'not_foi': not_foi,
        'object_list': foi_requests,
        'status_list': [(str(x[0]),
            x[2]) for x in FoiRequest.get_status_url()],
        'topic_list': topic_list

    return render(request, 'foirequest/list.html', context)

Example 35

Project: froide
Source File:
View license
def submit_request(request, public_body=None):
    error = False
    foi_law = None
    if public_body is not None:
        public_body = get_object_or_404(PublicBody,
        if not
            raise Http404
        all_laws = FoiLaw.objects.filter(jurisdiction=public_body.jurisdiction)
        all_laws = FoiLaw.objects.all()
    context = {"public_body": public_body}

    request_form = RequestForm(user=request.user,
    context['request_form'] = request_form
    context['public_body_form'] = PublicBodyForm()
    if (public_body is None and
            request.POST.get('public_body') == "new"):
        pb_form = PublicBodyForm(request.POST)
        context["public_body_form"] = pb_form
        if pb_form.is_valid():
            data = pb_form.cleaned_data
            data['confirmed'] = False
            # Take the first jurisdiction there is
            data['jurisdiction'] = Jurisdiction.objects.all()[0]
            data['slug'] = slugify(data['name'])
            public_body = PublicBody(**data)
            error = True

    if not request_form.is_valid():
        error = True
        if (public_body is None and
                request_form.cleaned_data['public_body'] != '' and
                request_form.cleaned_data['public_body'] != 'new'):
            public_body = request_form.public_body_object

    context['user_form'] = None
    user = None
    if not request.user.is_authenticated:
        user_form = NewUserForm(request.POST)
        context['user_form'] = user_form
        if not user_form.is_valid():
            error = True
        user = request.user

    if error:
        messages.add_message(request, messages.ERROR,
            _('There were errors in your form submission. Please review and submit again.'))
        return render(request, 'foirequest/request.html', context, status=400)

    password = None
    if user is None:
        user, password = AccountManager.create_user(**user_form.cleaned_data)
    sent_to_pb = 1
    if public_body is not None and is None:
        public_body._created_by = user
        sent_to_pb = 2
    elif public_body is None:
        sent_to_pb = 0

    if foi_law is None:
        if public_body is not None:
            foi_law = public_body.default_law
            foi_law = request_form.foi_law

    kwargs = registry.run_hook('pre_request_creation', request,
    foi_request = FoiRequest.from_request_form(**kwargs)

    special_redirect = None
    if request_form.cleaned_data['redirect_url']:
        redirect_url = request_form.cleaned_data['redirect_url']
        if is_safe_url(redirect_url, allowed_hosts=settings.ALLOWED_REDIRECT_HOSTS):
            special_redirect = redirect_url

    if user.is_active:
        if sent_to_pb == 0:
            messages.add_message(request, messages.INFO,
                _('Others can now suggest the Public Bodies for your request.'))
        elif sent_to_pb == 2:
            messages.add_message(request, messages.INFO,
                _('Your request will be sent as soon as the newly created Public Body was confirmed by an administrator.'))
            messages.add_message(request, messages.INFO,
                _('Your request has been sent.'))
        req_url = u'%s%s' % (foi_request.get_absolute_url(), _('?request-made'))
        return redirect(special_redirect or req_url)
        messages.add_message(request, messages.INFO,
                _('Please check your inbox for mail from us to confirm your mail address.'))
        # user cannot access the request yet, redirect to custom URL or homepage
        return redirect(special_redirect or "/")

Example 36

Project: django-forms-builder
Source File:
View license
    def entries_view(self, request, form_id, show=False, export=False,
        Displays the form entries in a HTML table with option to
        export as CSV file.
        if request.POST.get("back"):
            bits = (self.model._meta.app_label, self.model.__name__.lower())
            change_url = reverse("admin:%s_%s_change" % bits, args=(form_id,))
            return HttpResponseRedirect(change_url)
        form = get_object_or_404(self.model, id=form_id)
        post = request.POST or None
        args = form, request, self.formentry_model, self.fieldentry_model, post
        entries_form = EntriesForm(*args)
        delete = "%s.delete_formentry" % self.formentry_model._meta.app_label
        can_delete_entries = request.user.has_perm(delete)
        submitted = entries_form.is_valid() or show or export or export_xls
        export = export or request.POST.get("export")
        export_xls = export_xls or request.POST.get("export_xls")
        if submitted:
            if export:
                response = HttpResponse(content_type="text/csv")
                fname = "%s-%s.csv" % (form.slug, slugify(now().ctime()))
                attachment = "attachment; filename=%s" % fname
                response["Content-Disposition"] = attachment
                queue = StringIO()
                    csv = writer(queue, delimiter=CSV_DELIMITER)
                    writerow = csv.writerow
                except TypeError:
                    queue = BytesIO()
                    delimiter = bytes(CSV_DELIMITER, encoding="utf-8")
                    csv = writer(queue, delimiter=delimiter)
                    writerow = lambda row: csv.writerow([c.encode("utf-8")
                        if hasattr(c, "encode") else c for c in row])
                for row in entries_form.rows(csv=True):
                data = queue.getvalue()
                return response
            elif XLWT_INSTALLED and export_xls:
                response = HttpResponse(content_type="application/")
                fname = "%s-%s.xls" % (form.slug, slugify(now().ctime()))
                attachment = "attachment; filename=%s" % fname
                response["Content-Disposition"] = attachment
                queue = BytesIO()
                workbook = xlwt.Workbook(encoding='utf8')
                sheet = workbook.add_sheet(form.title[:31])
                for c, col in enumerate(entries_form.columns()):
                    sheet.write(0, c, col)
                for r, row in enumerate(entries_form.rows(csv=True)):
                    for c, item in enumerate(row):
                        if isinstance(item, datetime):
                            item = item.replace(tzinfo=None)
                            sheet.write(r + 2, c, item, XLWT_DATETIME_STYLE)
                            sheet.write(r + 2, c, item)
                data = queue.getvalue()
                return response
            elif request.POST.get("delete") and can_delete_entries:
                selected = request.POST.getlist("selected")
                if selected:
                        from django.contrib.messages import info
                    except ImportError:
                        def info(request, message, fail_silently=True):
                    entries = self.formentry_model.objects.filter(id__in=selected)
                    count = entries.count()
                    if count > 0:
                        message = ungettext("1 entry deleted",
                                            "%(count)s entries deleted", count)
                        info(request, message % {"count": count})
        template = "admin/forms/entries.html"
        context = {"title": _("View Entries"), "entries_form": entries_form,
                   "opts": self.model._meta, "original": form,
                   "can_delete_entries": can_delete_entries,
                   "submitted": submitted,
                   "xlwt_installed": XLWT_INSTALLED}
        return render(request, template, context)

Example 37

Project: tendenci
Source File:
View license
def register(request, success_url=None,
             form_class=RegistrationForm, profile_callback=None,
    Allow a new user to register an account.

    Following successful registration, issue a redirect; by default,
    this will be whatever URL corresponds to the named URL pattern
    ``registration_complete``, which will be
    ``/accounts/register/complete/`` if using the included URLConf. To
    change this, point that named pattern at another URL, or pass your
    preferred URL as the keyword argument ``success_url``.

    By default, ``registration.forms.RegistrationForm`` will be used
    as the registration form; to change this, pass a different form
    class as the ``form_class`` keyword argument. The form class you
    specify must have a method ``save`` which will create and return
    the new ``User``, and that method must accept the keyword argument
    ``profile_callback`` (see below).

    To enable creation of a site-specific user profile object for the
    new user, pass a function which will create the profile object as
    the keyword argument ``profile_callback``. See
    ``RegistrationManager.create_inactive_user`` in the file
    ```` for details on how to write this function.

    By default, use the template
    ``registration/registration_form.html``; to change this, pass the
    name of a template as the keyword argument ``template_name``.

    **Required arguments**


    **Optional arguments**

        The form class to use for registration.

        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

        A function which will be used to create a site-specific
        profile instance for the new ``User``.

        The URL to redirect to on successful registration.

        A custom template to use.


        The registration form.

    Any extra variables supplied in the ``extra_context`` argument
    (see above).


    registration/registration_form.html or ``template_name`` keyword

    # check if this site allows self registration, if not, redirect to login page
    allow_self_registration = get_setting('module', 'users', 'selfregistration')
    if not allow_self_registration:
        return HttpResponseRedirect(reverse('auth_login'))

    form_params = {}
    if request.session.get('form_params', None):
        form_params = request.session.pop('form_params')

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES, **form_params)
        if form.is_valid():
            # This is for including a link in the reg email back to the event viewed
            event = None
            if event_id: # the user signed up via an event
                from import Event
                event = get_object_or_404(Event, pk=event_id)

            new_user =, event=event)
            # success_url needs to be dynamically generated here; setting a
            # a default value using reverse() will cause circular-import
            # problems with the default URLConf for this application, which
            # imports this file.

            # add to the default group(s)
            default_user_groups =[g.strip() for g in (get_setting('module', 'users', 'defaultusergroup')).split(',')]
            if default_user_groups:
                from tendenci.apps.user_groups.models import Group, GroupMembership
                from django.db.models import Q
                for group_name in default_user_groups:
                    groups = Group.objects.filter(Q(name=group_name) | Q(label=group_name)).filter(allow_self_add=1, status=1, status_detail='active')
                    if groups:
                        group = groups[0]
                        # group doesnot exist, so create the group
                        group = Group()
                = group_name
                        group.label = group_name
                        group.type = 'distribution'
                        group.show_as_option = 1
                        group.allow_self_add = 1
                        group.allow_self_remove = 1
                        group.creator = new_user
                        group.creator_username = new_user.username
                        group.owner =  new_user
                        group.owner_username = new_user.username
                            group = None

                    if group:
                        gm = GroupMembership()
               = group
                        gm.member = new_user
                        gm.creator_id =
                        gm.creator_username = new_user.username
                        gm.owner_id =
                        gm.owner_username = new_user.username


            return HttpResponseRedirect(success_url or reverse('registration_complete'))
        elif form.similar_email_found:
                request, messages.INFO,
                _(u"An account already exists for the email %(email)s." % {
                    'email': request.POST.get('email_0') or request.POST.get('email_1')}))

            querystring = 'registration=True'
            return HttpResponseRedirect(reverse('auth_password_reset')+ "?%s" % querystring)

        allow_same_email = request.GET.get('registration_approved', False)
        form_params = {'allow_same_email' : allow_same_email }
        request.session['form_params'] = form_params
        form = form_class(**form_params)

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    return render_to_response(template_name,
                              { 'form': form },

Example 38

Project: tendenci
Source File:
View license
def multi_register(request, event_id, template_name="events/registration/multi_register.html"):
    This view is where a user defines the specifics of his/her registrations.
    A registration set is a set of registrants (one or many) that comply with a specific pricing.
    A pricing defines the maximum number of registrants in a registration set.
    A user can avail multiple registration sets.

    If the site setting anonymousmemberpricing is enabled,
    anonymous users can select non public pricings in their registration sets,
    provided that the first registrant of every registration set's email is validated to be an existing user.

    If the site setting anonymousmemberpricing is disabled,
    anonymous users will not be able to see non public prices.

    # redirect to default registration if anonymousmemberpricing not enabled
    if not get_setting('module', 'events', 'anonymousmemberpricing'):
        return redirect('event.multi_register', event_id)

    # clear user list session
    request.session['user_list'] = []

    event = get_object_or_404(Event, pk=event_id)

    # check if event allows registration
    if (event.registration_configuration is None or not event.registration_configuration.enabled):
        raise Http404

    # check if it is still open, always open for admin users
    if not request.user.profile.is_superuser:
        status = reg_status(event, request.user)
        if status == REG_FULL:
            messages.add_message(request, messages.ERROR, _('Registration is full.'))
            return redirect('event',
        elif status == REG_CLOSED:
            messages.add_message(request, messages.ERROR, _('Registration is closed.'))
            return redirect('event',

    user = AnonymousUser()
    # get available pricings
    active_pricings = get_active_pricings(event)
    event_pricings = event.registration_configuration.regconfpricing_set.all()

    # get available addons
    active_addons = get_active_addons(event)

    # check if use a custom reg form
    custom_reg_form = None
    reg_conf = event.registration_configuration
    if reg_conf.use_custom_reg_form:
        if reg_conf.bind_reg_form_to_conf_only:
            custom_reg_form = reg_conf.reg_form

    #custom_reg_form = None

    if custom_reg_form:
        RF = FormForCustomRegForm
        RF = RegistrantForm

    # start the form set factory
    RegistrantFormSet = formset_factory(

    RegAddonFormSet = formset_factory(

    if request.method == "POST":
        # process the submitted forms
        params = {'prefix': 'registrant',
                 'event': event,
                 'extra_params': {
        if custom_reg_form:
            params['extra_params'].update({"custom_reg_form": custom_reg_form,
                                           'event': event})
        reg_formset = RegistrantFormSet(request.POST,

        reg_form = RegistrationForm(event, request.user, request.POST,
                    reg_count = len(reg_formset.forms))

        # This form is just here to preserve the data in case of invalid registrants
        # The real validation of addons is after validation of registrants
        addon_formset = RegAddonFormSet(request.POST,

        # validate the form and formset
        if False not in (reg_form.is_valid(), reg_formset.is_valid()):
            valid_addons = get_addons_for_list(event, reg_formset.get_user_list())
            # validate the addons
            addon_formset = RegAddonFormSet(request.POST,
            if addon_formset.is_valid():
                # process the registration
                # this will create the registrants and apply the discount
                reg8n = process_registration(reg_form, reg_formset,  addon_formset, custom_reg_form=custom_reg_form)

                self_reg8n = get_setting('module', 'users', 'selfregistration')
                is_credit_card_payment = (reg8n.payment_method and
                    (reg8n.payment_method.machine_name).lower() == 'credit-card'
                    and reg8n.amount_paid > 0)
                registrants = reg8n.registrant_set.all().order_by('id')
                for registrant in registrants:
                    if registrant.custom_reg_form_entry:
               = registrant.custom_reg_form_entry.__unicode__()
               = ' '.join([registrant.first_name, registrant.last_name])

                if is_credit_card_payment: # online payment
                    # email the admins as well
                    email_admins(event, reg8n.amount_paid, self_reg8n, reg8n, registrants)
                    # get invoice; redirect to online pay
                    return redirect('payment.pay_online',
              , reg8n.invoice.guid)
                    # offline payment
                    # email the registrant
                    send_registrant_email(reg8n, self_reg8n)
                    # email the admins as well
                    email_admins(event, reg8n.amount_paid, self_reg8n, reg8n, registrants)


                # redirect to confirmation
                return redirect('event.registration_confirmation', event_id, reg8n.registrant.hash)
        params = {'prefix': 'registrant',
                    'event': event,
                    'extra_params': {
        if custom_reg_form:
            params['extra_params'].update({"custom_reg_form": custom_reg_form,
                                           'event': event})
        # intialize empty forms
        reg_formset = RegistrantFormSet(**params)
        reg_form = RegistrationForm(event, request.user)
        addon_formset = RegAddonFormSet(

    sets = reg_formset.get_sets()

    # build our hidden form dynamically
    hidden_form = None
    if custom_reg_form:
        params = {'prefix': 'registrant',
                  'event': event,
                  'extra_params': {
                        'custom_reg_form': custom_reg_form,
                        'event': event
        FormSet = formset_factory(
        formset = FormSet(**params)
        hidden_form = formset.forms[0]

    return render_to_response(template_name, {
            'custom_reg_form': custom_reg_form,
            'hidden_form': hidden_form,
            'registrant': reg_formset,
            'addon_formset': addon_formset,
            'sets': sets,
            'allow_memberid_pricing':get_setting('module', 'events', 'memberidpricing'),
            'shared_pricing':get_setting('module', 'events', 'sharedpricing'),
            }, context_instance=RequestContext(request))

Example 39

Project: tendenci
Source File:
View license
def details(request, id, size=None, crop=False, quality=90, download=False, constrain=False, template_name="files/details.html"):
    Return an image response after paramters have been applied.
    cache_key = generate_image_cache_key(

    cached_image = cache.get(cache_key)
    if cached_image:
        return redirect('%s%s' % (get_setting('site', 'global', 'siteurl'), cached_image))

    file = get_object_or_404(File, pk=id)

    # basic permissions
    if not has_view_perm(request.user, 'files.view_file', file):
        raise Http403

    # extra permission
    if not file.is_public:
        if not request.user.is_authenticated():
            raise Http403

    # if string and digit convert to integer
    if isinstance(quality, basestring) and quality.isdigit():
        quality = int(quality)

    # get image binary
        data =
    except IOError:  # no such file or directory
        raise Http404

    if download:  # log download
        attachment = u'attachment;'
            'event_id': 185000,
            'event_data': '%s %s (%d) dowloaded by %s' % (file.type(), file._meta.object_name,, request.user),
            'description': '%s downloaded' % file._meta.object_name,
            'user': request.user,
            'request': request,
            'instance': file,
    else:  # log view
        attachment = u''
        if file.type() != 'image':
                'event_id': 186000,
                'event_data': '%s %s (%d) viewed by %s' % (file.type(), file._meta.object_name,, request.user),
                'description': '%s viewed' % file._meta.object_name,
                'user': request.user,
                'request': request,
                'instance': file,

    # if image size specified
    if file.type() == 'image' and size:  # if size specified

        if file.ext() in ('.tif', '.tiff'):
            raise Http404  # tifs cannot (currently) be viewed via browsers

        size = [int(s) if s.isdigit() else 0 for s in size.split('x')]
        size = aspect_ratio(file.image_dimensions(), size, constrain)

        # check for dimensions
        # greater than zero
        if not all(size):
            raise Http404

        # gets resized image from cache or rebuilds
        image = get_image(file.file, size, FILE_IMAGE_PRE_KEY, cache=True, crop=crop, quality=quality, unique_key=None)
        response = HttpResponse(content_type=file.mime_type())
        response['Content-Disposition'] = '%s filename=%s' % (attachment, file.get_name())

        params = {'quality': quality}
        if image.format == 'GIF':
            params['transparency'] = 0, image.format, **params)

        if file.is_public_file():
            file_name = "%s%s" % (file.get_name(), ".jpg")
            file_path = 'cached%s%s' % (request.path, file_name)
  , ContentFile(response.content))
            full_file_path = "%s%s" % (settings.MEDIA_URL, file_path)
            cache.set(cache_key, full_file_path)
            cache_group_key = "files_cache_set.%s" %
            cache_group_list = cache.get(cache_group_key)

            if cache_group_list is None:
                cache.set(cache_group_key, [cache_key])
                cache_group_list += [cache_key]
                cache.set(cache_group_key, cache_group_list)

        return response

    if file.is_public_file():
        cache.set(cache_key, file.get_file_public_url())
        set_s3_file_permission(file.file, public=True)
        cache_group_key = "files_cache_set.%s" %
        cache_group_list = cache.get(cache_group_key)

        if cache_group_list is None:
            cache.set(cache_group_key, [cache_key])
            cache_group_list += cache_key
            cache.set(cache_group_key, cache_group_list)

    # set mimetype
    if file.mime_type():
        response = HttpResponse(data, content_type=file.mime_type())
        raise Http404

    # return response
    if file.get_name().endswith(file.ext()):
        response['Content-Disposition'] = '%s filename=%s' % (attachment, file.get_name())
        response['Content-Disposition'] = '%s filename=%s' % (attachment, file.get_name_ext())
    return response

Example 40

Project: tendenci
Source File:
View license
def form_detail(request, slug, template="forms/form_detail.html"):
    Display a built form and handle submission.
    published = Form.objects.published(for_user=request.user)
    form = get_object_or_404(published, slug=slug)

    if not has_view_perm(request.user,'forms.view_form',form):
        raise Http403

    # If form has a recurring payment, make sure the user is logged in
    if form.recurring_payment:
        [email_field] = form.fields.filter(field_type__iexact='EmailVerificationField')[:1] or [None]
        if request.user.is_anonymous() and not email_field:
            # anonymous user - if we don't have the email field, redirect to login
            response = redirect('auth_login')
            response['Location'] += '?next=%s' % form.get_absolute_url()
            return response
        if request.user.is_superuser and not email_field:
            messages.add_message(request, messages.WARNING,
                    'Please edit the form to include an email field ' + \
                    'as it is required for setting up a recurring ' + \
                    'payment for anonymous users.')

    form_for_form = FormForForm(form, request.user, request.POST or None, request.FILES or None)
    for field in form_for_form.fields:
        field_default = request.GET.get(field, None)
        if field_default:
            form_for_form.fields[field].initial = field_default

    if request.method == "POST":
        if form_for_form.is_valid():
            entry =
            entry.entry_path = request.POST.get("entry_path", "")
            if request.user.is_anonymous():
                if entry.get_email_address():
                    emailfield = entry.get_email_address()
                    firstnamefield = entry.get_first_name()
                    lastnamefield = entry.get_last_name()
                    phonefield = entry.get_phone_number()
                    password = ''
                    for i in range(0, 10):
                        password += random.choice(string.ascii_lowercase + string.ascii_uppercase)

                    user_list = User.objects.filter(email=emailfield).order_by('-last_login')
                    if user_list:
                        anonymous_creator = user_list[0]
                        anonymous_creator = User(username=emailfield[:30], email=emailfield,
                                                 first_name=firstnamefield, last_name=lastnamefield)
                        anonymous_creator.is_active = False
                        anonymous_profile = Profile(user=anonymous_creator, owner=anonymous_creator,
                                                    creator=anonymous_creator, phone=phonefield)
                    entry.creator = anonymous_creator
                entry.creator = request.user

            # Email
            subject = generate_email_subject(form, entry)
            email_headers = {}  # content type specified below
            if form.email_from:

            # Email to submitter
            # fields aren't included in submitter body to prevent spam
            submitter_body = generate_submitter_email_body(entry, form_for_form)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            is_spam = Email.is_blocked(email_to)
            if is_spam:
                # log the spam
                description = "Email \"{0}\" blocked because it is listed in email_blocks.".format(email_to)
                EventLog.objects.log(instance=form, description=description)
                if form.completion_url:
                    return HttpResponseRedirect(form.completion_url)
                return redirect("form_sent", form.slug)
            email = Email()
            email.subject = subject
            email.reply_to = form.email_from

            if email_to and form.send_email and form.email_text:
                # Send message to the person who submitted the form.
                email.recipient = email_to
                email.body = submitter_body

            # Email copies to admin
            admin_body = generate_admin_email_body(entry, form_for_form)
            email_from = email_to or email_from # Send from the email entered.
            email_headers = {}  # Reset the email_headers
            email_copies = [e.strip() for e in form.email_copies.split(',') if e.strip()]

            subject = subject.encode(errors='ignore')
            email_recipients = entry.get_function_email_recipients()
            # reply_to of admin emails goes to submitter
            email.reply_to = email_to

            if email_copies or email_recipients:
                # prepare attachments
                attachments = []
                    for f in form_for_form.files.values():
                except ValueError:
                    attachments = []
                    for field_entry in entry.fields.all():
                        if field_entry.field.field_type == 'FileField':
                                f =
                            except IOError:

                # Send message to the email addresses listed in the copies
                if email_copies:
                    email.body = admin_body
                    email.recipient = email_copies
                    email.send(fail_silently=True, attachments=attachments)

                # Email copies to recipient list indicated in the form
                if email_recipients:
                    email.body = admin_body
                    email.recipient = email_recipients
                    email.send(fail_silently=True, attachments=attachments)

            # payment redirect
            if (form.custom_payment or form.recurring_payment) and entry.pricing:
                # get the pricing's price, custom or otherwise
                price = entry.pricing.price or form_for_form.cleaned_data.get('custom_price')

                if form.recurring_payment:
                    if request.user.is_anonymous():
                        rp_user = entry.creator
                        rp_user = request.user
                    billing_start_dt =
                    trial_period_start_dt = None
                    trial_period_end_dt = None
                    if entry.pricing.has_trial_period:
                        trial_period_start_dt =
                        trial_period_end_dt = trial_period_start_dt + datetime.timedelta(1)
                        billing_start_dt = trial_period_end_dt
                    # Create recurring payment
                    rp = RecurringPayment(

                    # redirect to recurring payments
                    messages.add_message(request, messages.SUCCESS, _('Successful transaction.'))
                    return redirect('recurring_payment.view_account',, rp.guid)
                    # create the invoice
                    invoice = make_invoice_for_entry(entry, custom_price=price)
                    # log an event for invoice add


                    # redirect to billing form
                    return redirect('form_entry_payment',, invoice.guid)

            # default redirect
            if form.completion_url:
                return HttpResponseRedirect(form.completion_url)
            return redirect("form_sent", form.slug)

    # set form's template to forms/base.html if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "forms/base.html"

    # NOTE: Temporarily use forms/base.html for the meantime
    form.template = "forms/base.html"

    context = {
        "form": form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    return render_to_response(template, context, RequestContext(request))

Example 41

Project: tendenci
Source File:
View license
def add(request, form_class=JobForm, template_name="jobs/add.html",
        object_type=Job, success_redirect='job', thankyou_redirect='job.thank_you'):

    require_payment = get_setting('module', 'jobs',

    can_add_active = has_perm(request.user, 'jobs.add_job')

    content_type = get_object_or_404(

    if request.user.profile.is_superuser:
        category_form_class = CategoryForm
        category_form_class = CategoryForm2

    form = form_class(request.POST or None, request.FILES or None, user=request.user)
    # adjust the fields depending on user type
    if not require_payment:
        del form.fields['payment_method']
        del form.fields['list_type']

    if request.method == "POST":
        if require_payment:
            is_free = is_free_listing(request.user,
                               request.POST.get('pricing', 0),
            if is_free:
                del form.fields['payment_method']

        categoryform = category_form_class(

        if form.is_valid() and categoryform.is_valid():
            job =
            pricing = form.cleaned_data['pricing']

            if require_payment and is_free:
                job.payment_method = 'paid - cc'

            # set it to pending if the user is anonymous or not an admin
            if not can_add_active:
                #job.status = 1
                job.status_detail = 'pending'

            # list types and duration
            if not job.requested_duration:
                job.requested_duration = 30
            if not job.list_type:
                job.list_type = 'regular'

            # set up all the times
            now =
            job.activation_dt = now
            if not job.post_dt:
                job.post_dt = now

            # set the expiration date
            job.expiration_dt = job.activation_dt + timedelta(

            # semi-anon job posts don't get a slug field on the form
            # see __init__ method in JobForm
            if not job.slug:
                #job.slug = get_job_unique_slug(slugify(job.title))
                job.slug = '%s-%s' % (slugify(job.title),

            job = update_perms_and_save(request, form, job)

            # create invoice
            job_set_inv_payment(request.user, job, pricing)

            #setup categories
            category = Category.objects.get_for_object(job, 'category')
            sub_category = Category.objects.get_for_object(
                                                job, 'sub_category')

            ## update the category of the job
            category_removed = False
            category = categoryform.cleaned_data['category']
            if category != '0':
                Category.objects.update(job, category, 'category')
            else:  # remove
                category_removed = True
                Category.objects.remove(job, 'category')
                Category.objects.remove(job, 'sub_category')

            if not category_removed:
                # update the sub category of the job
                sub_category = categoryform.cleaned_data['sub_category']
                if sub_category != '0':
                    Category.objects.update(job, sub_category,
                else:  # remove

            #save relationships
            msg_string = 'Successfully added %s' % job
            messages.add_message(request, messages.SUCCESS,_(msg_string))

            # send notification to administrators
            recipients = get_notice_recipients(
                            'module', 'jobs', 'jobrecipients')
            if recipients:
                if notification:
                    extra_context = {
                        'object': job,
                        'request': request,
                    notification.send_emails(recipients, 'job_added',

            # send user to the payment page if payment is required
            if require_payment:
                if job.payment_method.lower() in ['credit card', 'cc']:
                    if job.invoice and job.invoice.balance > 0:
                        return HttpResponseRedirect(reverse(
                            args=[, job.invoice.guid])

            # send user to thank you or view page
            if request.user.profile.is_superuser:
                return HttpResponseRedirect(
                        reverse(success_redirect, args=[job.slug]))
                return HttpResponseRedirect(reverse(thankyou_redirect))
        # Redirect user w/perms to create pricing if none exist
        pricings = JobPricing.objects.all()
        if not pricings and has_perm(request.user, 'jobs.add_jobpricing'):
            msg_string = 'You need to add a %s Pricing before you can add a %s.' % (get_setting('module', 'jobs', 'label_plural'),get_setting('module', 'jobs', 'label'))
            messages.add_message(request, messages.WARNING, _(msg_string))
            return HttpResponseRedirect(reverse('job_pricing.add'))

        initial_category_form_data = {
            'app_label': 'jobs',
            'model': 'job',
            'pk': 0, #not used for this view but is required for the form
        categoryform = category_form_class(

    return render_to_response(template_name,
            {'form': form,
             'require_payment': require_payment,
             'categoryform': categoryform},

Example 42

Project: tendenci
Source File:
View license
def template_view(request, template_id, render=True):
    Generate newsletter preview
    Combine template with context passed via GET
    template = get_object_or_404(NewsletterTemplate, template_id=template_id)
    if not template.html_file:
        raise Http404

    if not has_perm(request.user, 'newsletters.view_newslettertemplate'):
        raise Http403

    simplified = True
    login_content = ""
    include_login = int(request.GET.get('include_login', 0))
    if include_login:
        login_content = render_to_string('newsletters/login.txt',

    jumplink_content = ""
    jump_links = int(request.GET.get('jump_links', 1))
    if jump_links:
        jumplink_content = render_to_string('newsletters/jumplinks.txt', locals(),

    art_content = ""
    articles = int(request.GET.get('articles', 1))
    articles_days = request.GET.get('articles_days', 60)
    if articles:
        articles_list, articles_content = newsletter_articles_list(request, articles_days, simplified)
        articles_list = []
        articles_content = []

    news_content = ""
    news = int(request.GET.get('news', 1))
    news_days = request.GET.get('news_days',30)
    if news:
        news_list, news_content = newsletter_news_list(request, news_days, simplified)
        news_list = []
        news_content = []

    jobs_content = ""
    jobs = int(request.GET.get('jobs', 1))
    jobs_days = request.GET.get('jobs_days', 30)
    if jobs:
        jobs_list, jobs_content = newsletter_jobs_list(request, jobs_days, simplified)
        jobs_list = []
        jobs_content = []

    pages_content = ""
    pages = int(request.GET.get('pages', 0))
    pages_days = request.GET.get('pages_days', 7)
    if pages:
        pages_list, pages_content = newsletter_pages_list(request, pages_days, simplified)
        pages_list = []
        pages_content = []

    directories_content = ""
    directories = int(request.GET.get('directories', 0))
    directories_days = request.GET.get('directories_days', 7)
    if directories:
        directories_list, directories_content = newsletter_directories_list(request, directories_days, simplified)
        directories_list = []
        directories_content = []

    resumes_content = ""
    resumes = int(request.GET.get('resumes', 0))
    resumes_days = request.GET.get('resumes_days', 7)
    if resumes:
        resumes_list, resumes_content = newsletter_resumes_list(request, resumes_days, simplified)
        resumes_list = []
        resumes_content = []

        events = int(request.GET.get('events', 1))
        events_type = request.GET.get('events_type')
        start_y, start_m, start_d = request.GET.get('event_start_dt', str('-')
        event_start_dt =, int(start_m), int(start_d))

        end_y, end_m, end_d = request.GET.get(
            str( + datetime.timedelta(days=90))).split('-')
        event_end_dt =, int(end_m), int(end_d))

        events_list, events_content = newsletter_events_list(

    except ImportError:
        events_list = []
        events_type = None

    text = DTemplate(apply_template_media(template))
    context = RequestContext(request,
                "art_content":articles_content, # legacy usage in templates
                "events":events_list, # legacy usage in templates
    content = text.render(context)

    if render:
        response = HttpResponse(content)
        return response
        return render_to_response(
            template_name, {
            'content': content,
            'template': template},

Example 43

Project: tendenci
Source File:
View license
def group_all_export(request, group_slug):
    Export all group members for a specific group
    group = get_object_or_404(Group, slug=group_slug)

    # if they can edit it, they can export it
    if not has_perm(request.user,'user_groups.change_group', group):
        raise Http403

    import xlwt
    from ordereddict import OrderedDict
    from django.db import connection
    from tendenci.apps.forms_builder.forms.models import FieldEntry

    # create the excel book and sheet
    book = xlwt.Workbook(encoding='utf8')
    sheet = book.add_sheet('Group Members and Subscribers')

    #initialize indexes
    row_index = {}
    col_index = {}

    # excel date styles
    default_style = xlwt.Style.default_style
    datetime_style = xlwt.easyxf(num_format_str='mm/dd/yyyy hh:mm')
    date_style = xlwt.easyxf(num_format_str='mm/dd/yyyy')

    # the key is what the column will be in the
    # excel sheet. the value is the database lookup
    # Used OrderedDict to maintain the column order
    group_mappings = OrderedDict([
        ('user_id', ''),
        ('first_name', 'au.first_name'),
        ('last_name', 'au.last_name'),
        ('email', ''),
        ('receives email', 'pp.direct_mail'),
        ('company', ''),
        ('address', 'pp.address'),
        ('address2', 'pp.address2'),
        ('city', ''),
        ('state', 'pp.state'),
        ('zipcode', 'pp.zipcode'),
        ('country', ''),
        ('phone', ''),
        ('is_active', 'au.is_active'),
        ('date', 'gm.create_dt'),
    group_lookups = ','.join(group_mappings.values())

    # Use custom sql to fetch the rows because we need to
    # populate the user profiles information and you
    # cannot do that with django's ORM without using
    # profile for each user query
    # pulling 13,000 group members can be done in one
    # query using Django's ORM but then you need
    # 13,000 individual queries :(
    cursor = connection.cursor()
    sql = "SELECT %s FROM user_groups_groupmembership gm \
           INNER JOIN auth_user au ON ( = gm.member_id) \
           LEFT OUTER JOIN profiles_profile pp \
           on (pp.user_id = gm.member_id) WHERE group_id = %%s;"
    sql =  sql % group_lookups
    cursor.execute(sql, [])
    values_list = list(cursor.fetchall())

    # index the group key mappings and insert them into the sheet.
    for key in group_mappings.keys():
        if not key in col_index:
            col = len(col_index.keys())
            col_index[key] = col
            sheet.write(0, col, key, style=default_style)

    if values_list:
        # Write the data enumerated to the excel sheet
        for row, row_data in enumerate(values_list):
            for col, val in enumerate(row_data):

                if not row in row_index:
                    # assign the row if it is not yet available
                    row_index[row] = row + 1

                # styles the date/time fields
                if isinstance(val, datetime):
                    style = datetime_style
                elif isinstance(val, date):
                    style = date_style
                    style = default_style

                sheet.write(row + 1, col, val, style=style)

    # Subscribers
    entries = FieldEntry.objects.filter(entry__subscriptions__group=group).distinct()

    for entry in entries:
        val = entry.value
        field = entry.field.label.lower().replace(" ", "_")

        if "subscriber %s" % str( in row_index:
            # get the subscriber's row number
            row = row_index["subscriber %s" % str(]
            # assign the row if it is not yet available
            row = len(row_index.keys()) + 1
            row_index["subscriber %s" % str(] = row

        if field in col_index:
            # get the entry's col number
            col = col_index[field]
            # assign the col if it is not yet available
            # and label the new column
            col = len(col_index.keys())
            col_index[field] = col
            sheet.write(0, col, field, style=default_style)

        # styles the date/time fields
        if isinstance(val, datetime):
            style = datetime_style
        elif isinstance(val, date):
            style = date_style
            style = default_style

        sheet.write(row, col, val, style=style)

    response = HttpResponse(content_type='application/')
    response['Content-Disposition'] = 'attachment; filename=group_%s_all_export.xls' %
    return response

Example 44

Project: hubplus
Source File:
View license
def details(request, id, template_name="photos/details.html"):
    show the photo details
    photo = get_object_or_404(Image, id=id)
    # @@@: test
    if not photo.is_public and request.user != photo.member:
        raise Http404
    photo_url = photo.get_display_url()
    tribes = []
    projects = []
    # Build a list of tribes and the photos from the pool
    for tribe in Tribe.objects.filter(members=request.user):
        phototribe = Tribe.objects.get(
                "slug": tribe.slug,
                "has_photo": True,
                "slug": tribe.slug,
                "has_photo": False,

    # Build a list of projects and the photos from the pool
    for project in Project.objects.filter(members__user=request.user):
        photoproject = Project.objects.get(
                "slug": project.slug,
                "has_photo": True,
                "slug": project.slug,
                "has_photo": False,

    title = photo.title
    host = "http://%s" % get_host(request)
    if photo.member == request.user:
        is_me = True
        is_me = False
    # TODO: check for authorized user and catch errors
    if is_me:
        if request.method == "POST" and request.POST["action"] == "add_to_project":
            projectid = request.POST["project"]
            myproject = Project.objects.get(pk=projectid)
            if not
                request.user.message_set.create(message=_("Successfully add photo '%s' to project") % title)
                # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                request.user.message_set.create(message=_("Did not add photo '%s' to project because it already exists.") % title)

            return HttpResponseRedirect(reverse('photo_details', args=(,)))
        if request.method == "POST":
            if request.POST["action"] == "addtotribe":
                tribeid = request.POST["tribe"]
                mytribe = Tribe.objects.get(pk=tribeid)
                if not
                    request.user.message_set.create(message=_("Successfully add photo '%s' to tribe") % title)
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not add photo '%s' to tribe because it already exists.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(,)))

            if request.POST["action"] == "removefromtribe":
                tribeid = request.POST["tribe"]
                mytribe = Tribe.objects.get(pk=tribeid)
                    request.user.message_set.create(message=_("Successfully removed photo '%s' from tribe") % title)
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not remove photo '%s' from tribe.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(,)))

            if request.POST["action"] == "addtoproject":
                projectid = request.POST["project"]
                myproject = Project.objects.get(pk=projectid)
                if not
                    request.user.message_set.create(message=_("Successfully add photo '%s' to project") % title)
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not add photo '%s' to project because it already exists.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(,)))

            if request.POST["action"] == "removefromproject":
                projectid = request.POST["project"]
                myproject = Project.objects.get(pk=projectid)
                    request.user.message_set.create(message=_("Successfully removed photo '%s' from project") % title)
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not remove photo '%s' from project.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(,)))

    return render_to_response(template_name, {
        "host": host, 
        "photo": photo,
        "photo_url": photo_url,
        "is_me": is_me,
        "projects": projects,
        "tribes": tribes,
    }, context_instance=RequestContext(request))

Example 45

Project: hubplus
Source File:
View license
def profile(request, username, template_name="profiles/profile.html"):
    #trellis.callInEventLoop(hello, "Tom")

    is_me = False
    user = request.user

    if request.user.is_authenticated() :
        if user.username == username :
            is_me = True
    else :
        user = get_anon_user()

    other_user = secure_wrap(get_object_or_404(User, username=username),user)

    is_following = Following.objects.is_following(request.user, other_user.get_inner())

    p = other_user.get_inner().get_profile()
    profile = secure_wrap(p,user)
    profile.user # trigger permission exception if no access
    can_change_avatar = False
    try :
        can_change_avatar = True
    except PlusPermissionsNoAccessException :

    interests = get_tags(tagged=other_user.get_inner().get_profile(), 
                         tagged_for=other_user.get_inner(), tag_type='interest')
    skills = get_tags(tagged = other_user.get_inner().get_profile(), 
                      tagged_for=other_user.get_inner(), tag_type='skill')
    needs = get_tags(tagged = other_user.get_inner().get_profile(), 
                     tagged_for=other_user.get_inner(), tag_type='need')

    user_type = ContentType.objects.get_for_model(other_user)

    # new style statuses
    tweets = FeedItem.feed_manager.get_from(other_user.get_inner()).order_by("-sent")
    if tweets :
        latest_status = tweets[0]
        status_since = defaultfilters.timesince(latest_status.sent)
        status_since = ''
    status_type = 'profile'

        perms_bool = True
    except PlusPermissionsNoAccessException:
        perms_bool = False

    profile = TemplateSecureWrapper(profile)

    search_type = 'profile_list' 
    search_types = narrow_search_types()
    search_types_len = len(search_types)
    search_type_label = search_types[0][1][2]

    host_info = p.get_host_info()
    host_info = secure_wrap(host_info, user, interface_names=['Viewer', 'Editor'])

    see_host_info = False
    try :
        see_host_info = True
    except :
        pass # can't see host_info
    host_info = TemplateSecureWrapper(host_info)
    hubs = other_user.get_inner().hubs()
    non_hub_groups = [(g.group_app_label() + ':group', g) for g in 
    hubs = [(g.group_app_label() + ':group', g) for g in hubs]

    see_about = is_me or show_section(profile, ('about',))
    see_contacts = is_me or show_section(profile,('mobile','home','work','fax','website','address','email_address'))
    see_links = is_me
    links = get_links_for(other_user,RequestContext(request))
    if links :
        see_links = True

    can_tag = profile.has_interface('Profile.Editor')

    template_args = {
            "is_me": is_me,
            "is_following": is_following,
            "other_user": other_user.get_inner(), # XXX - should fix this get_inner

            "head_title" : "%s" % profile.get_display_name(),
            "status_type" : status_type,
            "status_since" : status_since,
            "host_info" : host_info,
            "skills" : skills,
            "needs" : needs,
            "interests" : interests,
            "other_user_tweets" : tweets,
    labels = {'MAIN_HUB_LABEL':_('Main %s')%settings.HUB_NAME,
              'MAIN_HUB_DEFAULT':_("No %s selected")%settings.HUB_NAME}

    return render_to_response(template_name, template_args, context_instance=RequestContext(request))

Example 46

Project: ion
Source File:
View license
def events_view(request):
    """Events homepage.

    Shows a list of events occurring in the next week, month, and


    is_events_admin = request.user.has_admin_permission('events')

    if request.method == "POST":
        if "approve" in request.POST and is_events_admin:
            event_id = request.POST.get('approve')
            event = get_object_or_404(Event, id=event_id)
            event.rejected = False
            event.approved = True
            event.approved_by = request.user
            messages.success(request, "Approved event {}".format(event))

        if "reject" in request.POST and is_events_admin:
            event_id = request.POST.get('reject')
            event = get_object_or_404(Event, id=event_id)
            event.approved = False
            event.rejected = True
            event.rejected_by = request.user
            messages.success(request, "Rejected event {}".format(event))

    if is_events_admin and "show_all" in request.GET:
        viewable_events = (Event.objects.all().this_year().prefetch_related("groups"))
        viewable_events = (Event.objects.visible_to_user(request.user).this_year().prefetch_related("groups"))

    # get date objects for week and month
    today =
    delta = today - datetime.timedelta(days=today.weekday())
    this_week = (delta, delta + datetime.timedelta(days=7))
    this_month = (this_week[1], this_week[1] + datetime.timedelta(days=31))

    events_categories = [
            "title": "This week",
            "events": viewable_events.filter(time__gte=this_week[0], time__lt=this_week[1])
        }, {
            "title": "This month",
            "events": viewable_events.filter(time__gte=this_month[0], time__lt=this_month[1])
        }, {
            "title": "Future",
            "events": viewable_events.filter(time__gte=this_month[1])

    if is_events_admin:
        unapproved_events = (Event.objects.filter(approved=False, rejected=False).prefetch_related("groups"))
        events_categories = [{"title": "Awaiting Approval", "events": unapproved_events}] + events_categories

    if is_events_admin and "show_all" in request.GET:
        events_categories.append({"title": "Past", "events": viewable_events.filter(time__lt=this_week[0])})

    context = {
        "events": events_categories,
        "num_events": sum([x["events"].count() for x in events_categories]),
        "is_events_admin": is_events_admin,
        "events_admin": is_events_admin,
        "show_attend": True,
        "show_icon": True
    return render(request, "events/home.html", context)

Example 47

Project: mezzanine-recipes
Source File:
View license
def blog_post_list(request, model=BlogProxy, tag=None, year=None, month=None, username=None, category=None, template="blog/blog_post_list.html"):
    Display a list of blog posts that are filtered by tag, year, month,
    author or category. Custom templates are checked for using the name
    ``blog/blog_post_list_XXX.html`` where ``XXX`` is either the
    category slug or author's username if given.
    templates = []
    blog_posts = model.secondary.published(for_user=request.user)
    if tag is not None:
        tag = get_object_or_404(Keyword, slug=tag)
        blog_posts = blog_posts.filter(keywords__in=tag.assignments.all())
    if year is not None:
        blog_posts = blog_posts.filter(publish_date__year=year)
        if month is not None:
            blog_posts = blog_posts.filter(publish_date__month=month)
            month = month_name[int(month)]
    if category is not None:
        category = get_object_or_404(BlogCategory, slug=category)
        blog_posts = blog_posts.filter(categories=category)
        templates.append(u"blog/blog_post_list_%s.html" %
    author = None
    if username is not None:
        author = get_object_or_404(User, username=username)
        blog_posts = blog_posts.filter(user=author)
        templates.append(u"blog/blog_post_list_%s.html" % username)

    # We want to iterate keywords and categories for each blog post
    # without triggering "num posts x 2" queries.
    # For Django 1.3 we create dicts mapping blog post IDs to lists of
    # categories and keywords, and assign these to attributes on each
    # blog post. The Blog model then uses accessor methods to retrieve
    # these attributes when assigned, which will fall back to the real
    # related managers for Django 1.4 and higher, which will already
    # have their data retrieved via prefetch_related.

    blog_posts = blog_posts.select_related("user")
    if VERSION >= (1, 4):
        blog_posts = blog_posts.prefetch_related("categories",
        categories = defaultdict(list)
        if blog_posts:
            ids = ",".join([str( for p in blog_posts])
            for cat in BlogCategory.objects.raw(
                "SELECT * FROM blog_blogcategory "
                "JOIN blog_blogpost_categories "
                "ON = blogcategory_id "
                "WHERE blogpost_id IN (%s)" % ids):
        keywords = defaultdict(list)
        blogpost_type = ContentType.objects.get(app_label="blog",
        assigned = AssignedKeyword.objects.filter(blogpost__in=blog_posts,
        for a in assigned:
        for i, post in enumerate(blog_posts):
            setattr(blog_posts[i], "_categories", categories[])
            setattr(blog_posts[i], "_keywords", keywords[])

    blog_posts = paginate(blog_posts, request.GET.get("page", 1),
    context = {"blog_posts": blog_posts, "year": year, "month": month,
               "tag": tag, "category": category, "author": author}
    return render(request, templates, context)

Example 48

Project: pyas2
Source File:
View license
def as2receive(request, *args, **kwargs):
       Function receives AS2 requests from partners.
       Checks whether its an AS2 message or an MDN and acts accordingly.
    if request.method == 'POST':
        # Process the posted AS2 message
        request_body =

        # Create separate raw_payload with only message-id and content type as M2Crypto's signature
        # verification method does not like too many header
        raw_payload = '%s: %s\n' % ('message-id', request.META['HTTP_MESSAGE_ID'])
        raw_payload += '%s: %s\n\n' % ('content-type', request.META['CONTENT_TYPE'])
        raw_payload += request_body

        # Extract all the relevant headers from the http request
        as2headers = ''
        for key in request.META:
            if key.startswith('HTTP') or key.startswith('CONTENT'):
                as2headers += '%s: %s\n' % (key.replace("HTTP_", "").replace("_", "-").lower(), request.META[key])

        pyas2init.logger.debug('Recevied an HTTP POST from %s with payload :\n%s' %
                               (request.META['REMOTE_ADDR'], as2headers + '\n' + request_body))
            pyas2init.logger.debug('Check payload to see if its an AS2 Message or ASYNC MDN.')
            # Load the request header and body as a MIME Email Message
            payload = email.message_from_string(as2headers + '\n' + request_body)
            # Get the message sender and receiver AS2 IDs
            message_org = as2utils.unescape_as2name(payload.get('as2-to'))
            message_partner = as2utils.unescape_as2name(payload.get('as2-from'))
            message = None

            # Check if this is an MDN message
            mdn_message = None
            if payload.get_content_type() == 'multipart/report':
                mdn_message = payload
            elif payload.get_content_type() == 'multipart/signed':
                for part in payload.walk():
                    if part.get_content_type() == 'multipart/report':
                        mdn_message = part

            # If this is an MDN, get the message ID and check if it exists
            if mdn_message:
                msg_id = None

                for part in mdn_message.walk():
                    if part.get_content_type() == 'message/disposition-notification':
                        msg_id = part.get_payload().pop().get('Original-Message-ID')
      'Asynchronous MDN received for AS2 message %s to organization %s '
                                      'from partner %s' % (msg_id, message_org, message_partner))
                    # Get the related organization, partner and message from the db.
                    org = get_object_or_404(models.Organization, as2_name=message_org)
                    partner = get_object_or_404(models.Partner, as2_name=message_partner)
                    message = get_object_or_404(models.Message, message_id=msg_id.strip('<>'), organization=org, partner=partner)
                                              text=_(u'Processing asynchronous mdn received from partner'))
                    as2lib.save_mdn(message, raw_payload)

                except Http404:
                    # Send 404 response
                    pyas2init.logger.error('Unknown Asynchronous MDN AS2 message %s. '
                                           'Either the partner, org or message was not found in the system' % msg_id)
                    return HttpResponseServerError(_(u'Unknown AS2 MDN received. Will not be processed'))

                except Exception, e:
                    message.status = 'E'
                                              text=_(u'Failed to send message, error is %s' % e))

                    # Send mail here
                    as2utils.senderrorreport(message, _(u'Failed to send message, error is %s' % e))

                    # Save message and send response to HTTP request
                    if message:
                    return HttpResponse(_(u'AS2 ASYNC MDN has been received'))

                    # Process the received AS2 message from partner
                    # Initialize the processing status variables
                    status, adv_status, status_message = '', '', ''

          'Received an AS2 message with id %s for organization %s from partner %s' %
                                          (payload.get('message-id'), message_org, message_partner))

                    # Raise duplicate message error in case message already exists in the system
                    # TODO: Create composite key (message_id, organization, partner)
                    if models.Message.objects.filter(message_id=payload.get('message-id').strip('<>')).exists():
                        message = models.Message.objects.create(
                            message_id='%s_%s' % (payload.get('message-id').strip('<>'), payload.get('date')),
                        raise as2utils.As2DuplicateDocument(_(u'An identical message has already '
                                                              u'been sent to our server'))

                    # Create a new message in the system
                    message = models.Message.objects.create(

                    # Process the received payload to extract the actual message from partner
                    payload = as2lib.save_message(message, payload, raw_payload)

                    # Get the inbox folder for this partner and organization
                    output_dir = as2utils.join(pyas2init.gsettings['root_dir'],

                    # Get the filename from the header and if not there set to message id
                    if message.partner.keep_filename and payload.get_filename():
                        filename = payload.get_filename()
                        filename = '%s.msg' % message.message_id

                    # Save the message content to the store and inbox
                    content = payload.get_payload(decode=True)
                    full_filename = as2utils.storefile(output_dir, filename, content, False)
                    store_filename = as2utils.storefile(pyas2init.gsettings['payload_receive_store'],

                                              text=_(u'Message has been saved successfully to %s' % full_filename))
                    message.payload = models.Payload.objects.create(name=filename,

                    # Set processing status and run the post receive command.
                    status = 'success'
                    as2lib.run_post_receive(message, full_filename)

                # Catch each of the possible exceptions while processing an as2 message
                except as2utils.As2DuplicateDocument, e:
                    status = 'warning'
                    adv_status = 'duplicate-document'
                    status_message = _(u'An error occurred during the AS2 message processing: %s' % e)

                except as2utils.As2PartnerNotFound, e:
                    status = 'error'
                    adv_status = 'unknown-trading-partner'
                    status_message = _(u'An error occurred during the AS2 message processing: %s' % e)

                except as2utils.As2InsufficientSecurity, e:
                    status = 'error'
                    adv_status = 'insufficient-message-security'
                    status_message = _(u'An error occurred during the AS2 message processing: %s' % e)

                except as2utils.As2DecryptionFailed, e:
                    status = 'decryption-failed'
                    adv_status = 'error'
                    status_message = _(u'An error occurred during the AS2 message processing: %s' % e)

                except as2utils.As2DecompressionFailed, e:
                    status = 'error'
                    adv_status = 'decompression-failed'
                    status_message = _(u'An error occurred during the AS2 message processing: %s' % e)

                except as2utils.As2InvalidSignature, e:
                    status = 'error'
                    adv_status = 'integrity-check-failed'
                    status_message = _(u'An error occurred during the AS2 message processing: %s' % e)

                except Exception, e:
                    txt = traceback.format_exc(None).decode('utf-8', 'ignore')
                    pyas2init.logger.error(_(u'Unexpected error while processing message %(msg)s, '
                                             u'error:\n%(txt)s'), {'txt': txt, 'msg': message.message_id})
                    status = 'error'
                    adv_status = 'unexpected-processing-error'
                    status_message = _(u'An error occurred during the AS2 message processing: %s' % e)
                    # Build the mdn for the message based on processing status
                    mdn_body, mdn_message = as2lib.build_mdn(message,

                    # Create the mdn response body and return the MDN to the http request
                    if mdn_body:
                        mdn_response = HttpResponse(mdn_body, content_type=mdn_message.get_content_type())
                        for key, value in mdn_message.items():
                            mdn_response[key] = value
                        return mdn_response
                        return HttpResponse(_(u'AS2 message has been received'))

        # Catch all exception in case of any kind of error in the system.
        except Exception:
            txt = traceback.format_exc(None).decode('utf-8', 'ignore')
            report_txt = _(u'Fatal error while processing message %(msg)s, '
                           u'error:\n%(txt)s') % {'txt': txt, 'msg': request.META.get('HTTP_MESSAGE_ID').strip('<>')}
            return HttpResponseServerError(report_txt)
            # Send mail here
            # mail_managers(_(u'[pyAS2 Error Report] Fatal
            # error%(time)s')%{'time':request.META.get('HTTP_DATE')}, reporttxt)

    elif request.method == 'GET':
        return HttpResponse(_('To submit an AS2 message, you must POST the message to this URL '))

    elif request.method == 'OPTIONS':
        response = HttpResponse()
        response['allow'] = ','.join(['POST', 'GET'])
        return response

Example 49

Project: wagtail
Source File:
View license
def browse(request, parent_page_id=None):
    # A missing or empty page_type parameter indicates 'all page types'
    # (i.e. descendants of
    page_type_string = request.GET.get('page_type') or ''
        desired_classes = page_models_from_string(page_type_string)
    except (ValueError, LookupError):
        raise Http404

    # Find parent page
    if parent_page_id:
        parent_page = get_object_or_404(Page, id=parent_page_id)
    elif desired_classes == (Page,):
        # Just use the root page
        parent_page = Page.get_first_root_node()
        # Find the highest common ancestor for the specific classes passed in
        # In many cases, such as selecting an EventPage under an EventIndex,
        # this will help the administrator find their page quicker.
        all_desired_pages = filter_page_type(Page.objects.all(), desired_classes)
        parent_page = all_desired_pages.first_common_ancestor()

    # Get children of parent page
    pages = parent_page.get_children()

    # Filter them by page type
    if desired_classes != (Page,):
        # restrict the page listing to just those pages that:
        # - are of the given content type (taking into account class inheritance)
        # - or can be navigated into (i.e. have children)
        choosable_pages = filter_page_type(pages, desired_classes)
        descendable_pages = pages.filter(numchild__gt=0)
        pages = choosable_pages | descendable_pages

    can_choose_root = request.GET.get('can_choose_root', False)

    # Parent page can be chosen if it is a instance of desired_classes
    parent_page.can_choose = (
        issubclass(parent_page.specific_class or Page, desired_classes) and
        (can_choose_root or not parent_page.is_root())

    # Pagination
    # We apply pagination first so we don't need to walk the entire list
    # in the block below
    paginator, pages = paginate(request, pages, per_page=25)

    # Annotate each page with can_choose/can_decend flags
    for page in pages:
        if desired_classes == (Page, ):
            page.can_choose = True
            page.can_choose = issubclass(page.specific_class or Page, desired_classes)

        page.can_descend = page.get_children_count()

    # Render
    return render_modal_workflow(
        'wagtailadmin/chooser/browse.html', 'wagtailadmin/chooser/browse.js',
        shared_context(request, {
            'parent_page': parent_page,
            'pages': pages,
            'search_form': SearchForm(),
            'page_type_string': page_type_string,
            'page_type_names': [desired_class.get_verbose_name() for desired_class in desired_classes],
            'page_types_restricted': (page_type_string != '')

Example 50

Project: transifex
Source File:
View license
def translate(request, project_slug, lang_code, resource_slug=None,
                     *args, **kwargs):
    Main lotte view.

    # Permissions handling
    # Project should always be available
    project = get_object_or_404(Project, slug=project_slug)
    team = Team.objects.get_or_none(project, lang_code)
    check = ProjectPermission(request.user)
    if not check.submit_translations(team or project) and not\
        return permission_denied(request)

    resources = []
    if resource_slug:
        resource_list = [get_object_or_404(Resource, slug=resource_slug,
        resource_list = Resource.objects.filter(project=project)

        # Return a page explaining that the project has multiple source langs and
        # cannot be translated as a whole.
        if resource_list.values('source_language').distinct().count() > 1:
                          "There are multiple source languages for this project. "
                          "You will only be able to translate resources for one "
                          "source language at a time."))
            return HttpResponseRedirect(reverse('project_detail',

    # Filter resources that are not accepting translations
    for resource in resource_list:
        if resource.accept_translations:

    # If no resource accepting translations, raise a 403
    if not resources:
        return permission_denied(request)

    target_language = Language.objects.by_code_or_alias_or_404(lang_code)

    # If it is an attempt to edit the source language, redirect the user to
    # resource_detail and show him a message explaining the reason.
    if target_language == get_source_language(resources):
                       "Cannot edit the source language because this would "
                       "result in translation mismatches! If you want to "
                       "update the source strings consider using the transifex "
                       "command-line client."))
        if resource_slug:
            return HttpResponseRedirect(reverse('resource_detail',
            return HttpResponseRedirect(reverse('project_detail',

    total_strings = SourceEntity.objects.filter(
        resource__in = resources).count()

    translated_strings = Translation.objects.filter(

    reviewed_strings = Translation.objects.filter(

    # Include counting of pluralized entities
    for pluralized_entity in SourceEntity.objects.filter(resource__in = resources,
        plurals_translated = Translation.objects.filter(
        if plurals_translated == len(target_language.get_pluralrules()):
            translated_strings += 1

    if len(resources) > 1:
        translation_resource = None
        translation_resource = resources[0]

    contributors = User.objects.filter(pk__in=Translation.objects.filter(
        resource__in = resources,
        language = target_language,
        rule = 5).values_list("user", flat=True))

    lotte_init.send(None, request=request, resources=resources,

    if target_language in [team.language for team in project.available_teams]:
        team_language = True
        team_language = False

    GtModel = get_model('gtranslate', 'Gtranslate')
        auto_translate = GtModel.objects.get(project=project)
    except GtModel.DoesNotExist:
        auto_translate = None
    if cache.get('lotte_%s' % request.session.session_key, None):
        cache.delete('lotte_%s' % request.session.session_key)

    #Set rtl to True if target_language is an RTL language
    rtl = False
    if target_language.code in settings.RTL_LANGUAGE_CODES:
        rtl = True

    return render_to_response("translate.html", {
        'project': project,
        'resource': translation_resource,
        'target_language': target_language,
        'translated_strings': translated_strings,
        'reviewed_strings': reviewed_strings,
        'untranslated_strings': total_strings - translated_strings,
        'contributors': contributors,
        'resources': resources,
        'resource_slug': resource_slug,
        'languages': Language.objects.all(),
        'auto_translate': auto_translate,
        'spellcheck_supported_langs': SPELLCHECK_SUPPORTED_LANGS,
        'team_language': team_language,
        'RTL': rtl,
    }, context_instance = RequestContext(request))