django.shortcuts.render

Here are the examples of the python api django.shortcuts.render 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: views.py
View license
@login_required
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

    try:
        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_form.save(commit=False)
                review.user = request.user
                review.proposal = proposal
                review.save()

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

                message = message_form.save(commit=False)
                message.user = request.user
                message.proposal = proposal
                message.save()

                for speaker in speakers:
                    if speaker and speaker.email:
                        ctx = {
                            "proposal": proposal,
                            "message": message,
                            "reviewer": False,
                        }
                        send_email(
                            [speaker.email], "proposal_new_message",
                            context=ctx
                        )

                return redirect(request.path)
            else:
                initial = {}
                if latest_vote:
                    initial["vote"] = latest_vote.vote
                if request.user in speakers:
                    review_form = None
                else:
                    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"
                    proposal.result.save()
                elif result == "reject":
                    proposal.result.status = "rejected"
                    proposal.result.save()
                elif result == "undecide":
                    proposal.result.status = "undecided"
                    proposal.result.save()
                elif result == "standby":
                    proposal.result.status = "standby"
                    proposal.result.save()

            return redirect(request.path)
    else:
        initial = {}
        if latest_vote:
            initial["vote"] = latest_vote.vote
        if request.user in speakers:
            review_form = None
        else:
            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: builder
Source File: user.py
View license
@login_required
def userSettings(request):
  def createUserInfoForm(user):
    userInfo = m.UserInfo.objects.get(user=request.user)

    return UserInfoForm(
      initial={
        'company': userInfo.company,
        'email': user.email,
        'name': user.first_name,
        'website': userInfo.website,
      },
      user=request.user
    )

  if request.method == 'GET':
    return render(request, 'settings.tmpl', dict(
      userinfo_form=createUserInfoForm(request.user),
      password_form=PasswordForm()
    ))

  if request.method == 'POST':
    action = request.REQUEST.get('action', None)

    if action == 'change-pswd':
      user          = request.user
      password_form = PasswordForm(request.REQUEST, user = user)
      result        = None
      errorMsg      = None

      if password_form.is_valid():
        new = password_form.cleaned_data['new']
        user.set_password(new)
        user.save()

        salt = m.UserInfo.objects.get(user=user).secure_storage_salt
        request.session['secureStorageKey'] = secureStorage.getEncryptionKey(new, salt)

        result = 'success'
      else:
        if password_form.errors.get('__all__', None):
          errorMsg = password_form.errors['__all__'][0]
        else:
          errorMsg = "There was an error while updating the password."

        result = 'error'

      return render(request, 'settings.tmpl', dict(
        userinfo_form = createUserInfoForm(request.user),
        password_form = password_form,
        action        = action,
        result        = result,
        errorMsg      = errorMsg
      ))

    if action == 'update-info':
      user          = request.user
      userinfo_form = UserInfoForm(request.REQUEST, user = user)
      result        = None
      errorMsg      = None

      if userinfo_form.is_valid():
        user.email      = userinfo_form.cleaned_data['email']
        user.first_name = userinfo_form.cleaned_data['name']
        try:
          user.save()
        except django.db.IntegrityError:
          # TODO - error must be handled here.
          logging.exception('error while changing the email of the user.')
        else:
          # update the company info.
          userinfo         = user.userinfo
          userinfo.company = userinfo_form.cleaned_data['company']
          userinfo.website = userinfo_form.cleaned_data['website']
          userinfo.save()

          result = 'success'
      else:
        if userinfo_form.errors.get('__all__', None):
          errorMsg = userinfo_form.errors['__all__'][0]
        else:
          errorMsg = "There was an error while updating the personal information."

        result = 'error'

      return render(request, 'settings.tmpl', dict(
        userinfo_form = userinfo_form,
        password_form = PasswordForm(),
        action        = action,
        result        = result,
        errorMsg      = errorMsg
      ))

    return render(request, 'settings.tmpl')

Example 3

Project: builder
Source File: user.py
View license
@login_required
def userSettings(request):
  def createUserInfoForm(user):
    userInfo = m.UserInfo.objects.get(user=request.user)

    return UserInfoForm(
      initial={
        'company': userInfo.company,
        'email': user.email,
        'name': user.first_name,
        'website': userInfo.website,
      },
      user=request.user
    )

  if request.method == 'GET':
    return render(request, 'settings.tmpl', dict(
      userinfo_form=createUserInfoForm(request.user),
      password_form=PasswordForm()
    ))

  if request.method == 'POST':
    action = request.REQUEST.get('action', None)

    if action == 'change-pswd':
      user          = request.user
      password_form = PasswordForm(request.REQUEST, user = user)
      result        = None
      errorMsg      = None

      if password_form.is_valid():
        new = password_form.cleaned_data['new']
        user.set_password(new)
        user.save()

        salt = m.UserInfo.objects.get(user=user).secure_storage_salt
        request.session['secureStorageKey'] = secureStorage.getEncryptionKey(new, salt)

        result = 'success'
      else:
        if password_form.errors.get('__all__', None):
          errorMsg = password_form.errors['__all__'][0]
        else:
          errorMsg = "There was an error while updating the password."

        result = 'error'

      return render(request, 'settings.tmpl', dict(
        userinfo_form = createUserInfoForm(request.user),
        password_form = password_form,
        action        = action,
        result        = result,
        errorMsg      = errorMsg
      ))

    if action == 'update-info':
      user          = request.user
      userinfo_form = UserInfoForm(request.REQUEST, user = user)
      result        = None
      errorMsg      = None

      if userinfo_form.is_valid():
        user.email      = userinfo_form.cleaned_data['email']
        user.first_name = userinfo_form.cleaned_data['name']
        try:
          user.save()
        except django.db.IntegrityError:
          # TODO - error must be handled here.
          logging.exception('error while changing the email of the user.')
        else:
          # update the company info.
          userinfo         = user.userinfo
          userinfo.company = userinfo_form.cleaned_data['company']
          userinfo.website = userinfo_form.cleaned_data['website']
          userinfo.save()

          result = 'success'
      else:
        if userinfo_form.errors.get('__all__', None):
          errorMsg = userinfo_form.errors['__all__'][0]
        else:
          errorMsg = "There was an error while updating the personal information."

        result = 'error'

      return render(request, 'settings.tmpl', dict(
        userinfo_form = userinfo_form,
        password_form = PasswordForm(),
        action        = action,
        result        = result,
        errorMsg      = errorMsg
      ))

    return render(request, 'settings.tmpl')

Example 4

Project: vumi-go
Source File: views.py
View license
@login_required
@csrf_protect
def _static_group(request, contact_store, group):
    if group is None:
        raise Http404

    if request.method == 'POST':
        group_form = ContactGroupForm(request.POST)
        if '_save_group' in request.POST:
            if group_form.is_valid():
                group.name = group_form.cleaned_data['name']
                group.save()
            messages.info(request, 'The group name has been updated')
            return redirect(_group_url(group.key))
        elif '_export' in request.POST:
            tasks.export_group_contacts.delay(
                request.user_api.user_account_key,
                group.key)

            messages.info(request,
                          'The export is scheduled and should '
                          'complete within a few minutes.')
            return redirect(_group_url(group.key))
        elif '_remove' in request.POST:
            contacts = request.POST.getlist('contact')
            for person_key in contacts:
                contact = contact_store.get_contact_by_key(person_key)
                contact.groups.remove(group)
                contact.save()
            messages.info(
                request,
                '%d Contacts removed from group' % len(contacts))
            return redirect(_group_url(group.key))
        elif '_delete_group_contacts' in request.POST:
            tasks.delete_group_contacts.delay(
                request.user_api.user_account_key, group.key)
            messages.info(request,
                          "The group's contacts will be deleted shortly.")
            return redirect(_group_url(group.key))
        elif '_delete_group' in request.POST:
            tasks.delete_group.delay(request.user_api.user_account_key,
                                     group.key)
            messages.info(request, 'The group will be deleted shortly.')
            return redirect(reverse('contacts:index'))
        elif '_complete_contact_upload' in request.POST:
            try:
                import_rule = request.POST.get('import_rule')
                import_handler = {
                    'existing_is_truth': handle_import_existing_is_truth,
                    'upload_is_truth': handle_import_upload_is_truth,
                }.get(import_rule, handle_import_new_contacts)

                import_handler(request, group)
                messages.info(
                    request,
                    'The contacts are being imported. '
                    'We will notify you via email when the import '
                    'has been completed')

            except (ContactParserException, ContactImportException), e:
                if isinstance(e, ContactImportException):
                    error_msg = str(e)
                else:
                    error_msg = 'Something is wrong with the file'
                messages.error(request, error_msg)
                _, file_path = utils.get_file_hints_from_session(request)
                default_storage.delete(file_path)
                utils.clear_file_hints_from_session(request)

            return redirect(_group_url(group.key))

        else:
            upload_contacts_form = UploadContactsForm(request.POST,
                                                      request.FILES)
            if upload_contacts_form.is_valid():
                file_object = upload_contacts_form.cleaned_data['file']
                file_name, file_path = utils.store_temporarily(file_object)
                utils.store_file_hints_in_session(
                    request, file_name, file_path)
                return redirect(_group_url(group.key))
            else:
                # We didn't get any useful POST variables, so just redirect
                # back to the group page without doing anything.
                return redirect(_group_url(group.key))

    else:
        group_form = ContactGroupForm({
            'name': group.name,
        })

    context = {
        'group': group,
        'group_form': group_form,
    }

    if 'clear-upload' in request.GET:
        # FIXME this is a debug statement
        utils.clear_file_hints_from_session(request)

    if utils.has_uncompleted_contact_import(request):
        try:
            file_name, file_path = utils.get_file_hints_from_session(request)
            file_type, parser = ContactFileParser.get_parser(file_name)
            has_header, headers, row = parser.guess_headers_and_row(file_path)
            context.update({
                'contact_data_headers': headers,
                'field_normalizer': FieldNormalizer(),
                'contact_data_row': row,
                # NOTE: Only if we have a key (contact UUID) value in the
                #       row we can look at updating contacts instead of
                #       only writing new ones.
                'can_update_contacts': 'key' in row,
            })
        except (ValueError, ContactParserException):
            messages.error(request, 'Something is wrong with the file')
            utils.clear_file_hints_from_session(request)
            default_storage.delete(file_path)

    query = request.GET.get('q', '')
    if query:
        if ':' not in query:
            query = 'name:%s' % (query,)
        keys_page = contact_store.search_contacts(query)
    else:
        keys_page = contact_store.get_contact_keys_for_group(group)

    limit = int(request.GET.get('limit', 100))
    count, keys = _get_count_and_keys_from_index(keys_page, limit)
    if keys:
        messages.info(
            request,
            "Showing %s of the group's %s contact(s)" % (len(keys), count))

    contacts = utils.contacts_by_key(contact_store, *keys)
    context.update({
        'query': request.GET.get('q'),
        'selected_contacts': contacts,
        'member_count': contact_store.count_contacts_for_group(group),
    })

    return render(request, 'contacts/static_group_detail.html', context)

Example 5

Project: vumi-go
Source File: views.py
View license
@login_required
@csrf_protect
def _people(request):
    contact_store = request.user_api.contact_store
    upload_contacts_form = None
    group = None

    if request.method == 'POST':
        if '_delete' in request.POST:
            contacts = request.POST.getlist('contact')
            for person_key in contacts:
                contact = contact_store.get_contact_by_key(person_key)
                contact.delete()
            messages.info(request, '%d Contacts deleted' % len(contacts))
        elif '_export' in request.POST:
            tasks.export_contacts.delay(
                request.user_api.user_account_key,
                request.POST.getlist('contact'))
            messages.info(request, 'The export is scheduled and should '
                                   'complete within a few minutes.')
        elif '_export_all' in request.POST:
            tasks.export_all_contacts.delay(
                request.user_api.user_account_key)
            messages.info(request, 'The export is scheduled and should '
                                   'complete within a few minutes.')
        else:
            # first parse the CSV file and create Contact instances
            # from them for attaching to a group later
            upload_contacts_form = UploadContactsForm(
                request.POST, request.FILES)
            if upload_contacts_form.is_valid():
                # We could be creating a new contact group.
                if request.POST.get('name'):
                    new_group_form = ContactGroupForm(request.POST)
                    if new_group_form.is_valid():
                        group = contact_store.new_group(
                            new_group_form.cleaned_data['name'])

                # We could be using an existing contact group.
                elif request.POST.get('contact_group'):
                    select_group_form = SelectContactGroupForm(
                        request.POST, groups=contact_store.list_groups())
                    if select_group_form.is_valid():
                        group = contact_store.get_group(
                            select_group_form.cleaned_data['contact_group'])

                if group is None:
                    messages.error(request, 'Please select a group or provide '
                                            'a new group name.')
                else:
                    file_object = upload_contacts_form.cleaned_data['file']
                    file_name, file_path = utils.store_temporarily(file_object)
                    utils.store_file_hints_in_session(
                        request, file_name, file_path)
                    return redirect(_group_url(group.key))
            else:
                messages.error(
                    request, 'Something went wrong with the upload.')

    select_contact_group_form = SelectContactGroupForm(
        groups=contact_store.list_groups())

    # TODO: A lot of this stuff is duplicated from the similar group search
    #       in the groups() view. We need a function that does that to avoid
    #       the duplication.
    user_query = request.GET.get('q', '')
    query = user_query
    # The _fetch_limit param is mostly for testing, but may be useful as a
    # production hack if we really need to count all contacts or something.
    fetch_limit = int(request.GET.get('_fetch_limit', 10000))
    if query:
        if ':' not in query:
            query = 'name:%s' % (query,)

        # TODO: Use pagination here.
        keys = contact_store.contacts.raw_search(query).get_keys()
    else:
        keys = contact_store.list_contacts_page(max_results=fetch_limit)

    key_count = len(keys)
    limit = min(int(request.GET.get('limit', 100)), key_count)
    # If we have a continuation token, it means there are more than
    # `fetch_limit` keys.
    if getattr(keys, 'continuation', None) is not None:
        key_count = "%s+" % (fetch_limit,)
    messages.info(request, "Showing %s of %s contact(s)" % (limit, key_count))

    smart_group_form = SmartGroupForm(initial={'query': query})
    contacts = utils.contacts_by_key(contact_store, *list(keys)[:limit])

    return render(request, 'contacts/contact_list.html', {
        'query': user_query,
        'selected_contacts': contacts,
        'smart_group_form': smart_group_form,
        'upload_contacts_form': upload_contacts_form or UploadContactsForm(),
        'select_contact_group_form': select_contact_group_form,
    })

Example 6

Project: pycon
Source File: views.py
View license
@login_required
def proposal_speaker_manage(request, pk):
    queryset = ProposalBase.objects.select_related("speaker")
    proposal = get_object_or_404(queryset, pk=pk)
    proposal = ProposalBase.objects.get_subclass(pk=proposal.pk)

    if proposal.speaker != request.user.speaker_profile:
        raise Http404()

    if request.method == "POST":
        add_speaker_form = AddSpeakerForm(request.POST, proposal=proposal)
        if add_speaker_form.is_valid():
            message_ctx = {
                "proposal": proposal,
            }

            def create_speaker_token(email_address):
                # create token and look for an existing speaker to prevent
                # duplicate tokens and confusing the pending speaker
                try:
                    pending = Speaker.objects.get(
                        Q(invite_email=email_address)
                    )
                except Speaker.DoesNotExist:
                    salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
                    token = hashlib.sha1(salt + email_address).hexdigest()
                    pending = Speaker.objects.create(
                        invite_email=email_address,
                        invite_token=token,
                    )
                else:
                    token = pending.invite_token
                return pending, token

            email_address = add_speaker_form.cleaned_data["email"]

            # django-selectable widget will return a User for emails that are
            # associated with a current User, else a string
            if isinstance(email_address, User):
                email_address = email_address.email

            # check if email is on the site now
            users = EmailAddress.objects.get_users_for(email_address)
            if users:
                # should only be one since we enforce unique email
                user = users[0]
                message_ctx["user"] = user
                # look for speaker profile
                try:
                    speaker = user.speaker_profile
                except ObjectDoesNotExist:
                    speaker, token = create_speaker_token(email_address)
                    message_ctx["token"] = token
                    # fire off email to user to create profile
                    send_email(
                        [email_address], "speaker_no_profile",
                        context = message_ctx
                    )
                else:
                    # fire off email to user letting them they are loved.
                    send_email(
                        [email_address], "speaker_addition",
                        context = message_ctx
                    )
            else:
                speaker, token = create_speaker_token(email_address)
                message_ctx["token"] = token
                # fire off email letting user know about site and to create
                # account and speaker profile
                send_email(
                    [email_address], "speaker_invite",
                    context = message_ctx
                )
            invitation, created = AdditionalSpeaker.objects.get_or_create(proposalbase=proposal.proposalbase_ptr, speaker=speaker)
            messages.success(request, "Speaker invited to proposal.")
            return redirect("proposal_speaker_manage", proposal.pk)
    else:
        add_speaker_form = AddSpeakerForm(proposal=proposal)

    ctx = {
        "proposal": proposal,
        "speakers": proposal.speakers(),
        "add_speaker_form": add_speaker_form,
    }
    return render(request, "proposals/proposal_speaker_manage.html", ctx)

Example 7

Project: pycon
Source File: views.py
View license
@login_required
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

    try:
        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)
            else:
                review_form = NonVotingReviewForm(request.POST)
            if review_form.is_valid():

                review = review_form.save(commit=False)
                review.user = request.user
                review.proposal = proposal
                review.save()

                return redirect(request.path)
            else:
                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']
                proposal.tags.set(*tags)

                return redirect(request.path)
            else:
                message_form = SpeakerCommentForm()
                if request.user not in speakers:
                    initial = {}
                    if latest_vote:
                        initial["vote"] = latest_vote.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_form.save(commit=False)
                message.user = request.user
                message.proposal = proposal
                message.save()

                for speaker in speakers:
                    if speaker and speaker.email:
                        ctx = {
                            "proposal": proposal,
                            "message": message,
                            "reviewer": False,
                        }
                        send_email(
                            [speaker.email], "proposal_new_message",
                            context=ctx
                        )

                return redirect(request.path)
            else:
                initial = {}
                if latest_vote:
                    initial["vote"] = latest_vote.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"
                    proposal.result.save()
                elif result == "reject":
                    proposal.result.status = "rejected"
                    proposal.result.save()
                elif result == "undecide":
                    proposal.result.status = "undecided"
                    proposal.result.save()
                elif result == "standby":
                    proposal.result.status = "standby"
                    proposal.result.save()

            return redirect(request.path)
    else:
        initial = {}
        if latest_vote:
            initial["vote"] = latest_vote.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 8

Project: djangopackages
Source File: views.py
View license
def homepage(request, template_name="homepage.html"):

    categories = []
    for category in Category.objects.annotate(package_count=Count("package")):
        element = {
            "title": category.title,
            "description": category.description,
            "count": category.package_count,
            "slug": category.slug,
            "title_plural": category.title_plural,
            "show_pypi": category.show_pypi,
        }
        categories.append(element)

    # get up to 5 random packages
    package_count = Package.objects.count()
    random_packages = []
    if package_count > 1:
        package_ids = set([])

        # Get 5 random keys
        package_ids = sample(
            range(1, package_count + 1),  # generate a list from 1 to package_count +1
            min(package_count, 5)  # Get a sample of the smaller of 5 or the package count
        )

        # Get the random packages
        random_packages = Package.objects.filter(pk__in=package_ids)[:5]

    try:
        potw = Dpotw.objects.latest().package
    except Dpotw.DoesNotExist:
        potw = None
    except Package.DoesNotExist:
        potw = None

    try:
        gotw = Gotw.objects.latest().grid
    except Gotw.DoesNotExist:
        gotw = None
    except Grid.DoesNotExist:
        gotw = None

    # Public Service Announcement on homepage
    try:
        psa_body = PSA.objects.latest().body_text
    except PSA.DoesNotExist:
        psa_body = '<p>There are currently no announcements.  To request a PSA, tweet at <a href="http://twitter.com/open_comparison">@Open_Comparison</a>.</p>'

    # Latest Django Packages blog post on homepage

    feed_result = get_feed()
    if len(feed_result.entries):
        blogpost_title = feed_result.entries[0].title
        blogpost_body = feed_result.entries[0].summary
    else:
        blogpost_title = ''
        blogpost_body = ''

    return render(request,
        template_name, {
            "latest_packages": Package.objects.all().order_by('-created')[:5],
            "random_packages": random_packages,
            "potw": potw,
            "gotw": gotw,
            "psa_body": psa_body,
            "blogpost_title": blogpost_title,
            "blogpost_body": blogpost_body,
            "categories": categories,
            "package_count": package_count,
            "py3_compat": Package.objects.filter(version__supports_python3=True).select_related().distinct().count(),
            "latest_python3": Version.objects.filter(supports_python3=True).select_related("package").distinct().order_by("-created")[0:5]
        }
    )

Example 9

Project: junction
Source File: dashboard.py
View license
@login_required
@require_http_methods(['GET'])
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(
        conference=conference,
        status=ProposalStatus.PUBLIC)

    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(pro_type.id, [0, 0, 0, pro_type.name])
        by_type[pro_type.id][0] = by_type[pro_type.id][0] + 1
        by_section.setdefault(section.id, [0, 0, 0, section.name])
        by_section[section.id][0] = by_section[section.id][0] + 1
        private_comment_count = \
            ProposalComment.objects.filter(
                proposal=proposal,
                deleted=False,
                private=True).count()
        if private_comment_count:
            reviewed_count = reviewed_count + 1
            by_type[pro_type.id][1] = by_type[pro_type.id][1] + 1
            by_section[section.id][1] = by_section[section.id][1] + 1
        else:
            unreviewed_count = unreviewed_count + 1
            by_type[pro_type.id][2] = by_type[pro_type.id][2] + 1
            by_section[section.id][2] = by_section[section.id][2] + 1
    sections = \
        ProposalSectionReviewer.objects.filter(
            conference_reviewer__reviewer=request.user)\
        .distinct('proposal_section__id')
    # Hande case if reviewer is added to section twice'

    for section in sections:
        proposal_qs = proposals_qs.filter(
            proposal_section=section.proposal_section)
        # due to space and number issue for key used this
        key_id = '%s' % section.proposal_section.id
        by_reviewer.setdefault(
            key_id,
            [proposal_qs.count(), 0, 0, section.proposal_section.name])
        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
            else:
                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 = \
            ProposalComment.objects.filter(
                proposal=proposal,
                deleted=False,
                private=True).count()
        if private_comment_count:
            by_audience[audience][1] = by_audience[audience][1] + 1
            by_audience[audience][0] = by_audience[audience][0] + 1
        else:
            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 10

Project: pyconkr-2015
Source File: views.py
View license
@login_required
def registration_payment(request):
    max_ticket_limit = settings.MAX_TICKET_NUM

    if not is_registration_time():
        return redirect('registration_info')

    if request.method == 'GET':
        product = Product()

        registered = Registration.objects.filter(
            user=request.user,
            payment_status__in=['paid', 'ready']
        ).exists()

        if registered:
            return redirect('registration_status')

        uid = str(uuid4()).replace('-', '')
        form = RegistrationForm(initial={'email': request.user.email})

        return render(request, 'pyconkr/registration/payment.html', {
            'title': _('Registration'),
            'IMP_USER_CODE': settings.IMP_USER_CODE,  # TODO : Move to 'settings context processor'
            'form': form,
            'uid': uid,
            'product_name': product.name,
            'amount': product.price,
            'vat': 0,
        })
    elif request.method == 'POST':
        payment_logger.debug(request.POST)
        form = RegistrationForm(request.POST)

        # TODO : more form validation
        # eg) merchant_uid
        if not form.is_valid():
            form_errors_string = "\n".join(('%s:%s' % (k, v[0]) for k, v in form.errors.items()))
            return render_json({
                'success': False,
                'message': form_errors_string,  # TODO : ...
            })

        remain_ticket_count = (settings.MAX_TICKET_NUM - Registration.objects.filter(payment_status__in=['paid', 'ready']).count())

        # sold out
        if remain_ticket_count <= 0:
            return render_json({
                'success': False,
                'message': u'티켓이 매진 되었습니다',
            })

        registration, created = Registration.objects.get_or_create(user=request.user)
        registration.name = form.cleaned_data.get('name')
        registration.email = request.user.email
        registration.company = form.cleaned_data.get('company', '')
        registration.phone_number = form.cleaned_data.get('phone_number', '')
        registration.merchant_uid = request.POST.get('merchant_uid')
        registration.save()  # TODO : use form.save()

        try:
            product = Product()
            access_token = get_access_token(settings.IMP_API_KEY, settings.IMP_API_SECRET)
            imp_client = Iamporter(access_token)

            if request.POST.get('payment_method') == 'card':
                # TODO : use validated and cleaned data
                imp_client.onetime(
                    token=request.POST.get('token'),
                    merchant_uid=request.POST.get('merchant_uid'),
                    amount=request.POST.get('amount'),
                    # vat=request.POST.get('vat'),
                    card_number=request.POST.get('card_number'),
                    expiry=request.POST.get('expiry'),
                    birth=request.POST.get('birth'),
                    pwd_2digit=request.POST.get('pwd_2digit'),
                    customer_uid=form.cleaned_data.get('email'),
                )

            confirm = imp_client.find_by_merchant_uid(request.POST.get('merchant_uid'))

            if confirm['amount'] != product.price:
                # TODO : cancel
                return render_io_error("amount is not same as product.price. it will be canceled")

            registration.payment_method = confirm.get('pay_method')
            registration.payment_status = confirm.get('status')
            registration.payment_message = confirm.get('fail_reason')
            registration.vbank_name = confirm.get('vbank_name', None)
            registration.vbank_num = confirm.get('vbank_num', None)
            registration.vbank_date = confirm.get('vbank_date', None)
            registration.vbank_holder = confirm.get('vbank_holder', None)
            registration.save()

            send_email_ticket_confirm(request, registration)
        except IamporterError as e:
            # TODO : other status code
            return render_json({
                'success': False,
                'code': e.code,
                'message': e.message,
            })
        else:
            return render_json({
                'success': True,
            })

Example 11

Project: allianceauth
Source File: views.py
View license
@login_required
def corp_member_view(request, corpid=None, year=datetime.date.today().year, month=datetime.date.today().month):
    year = int(year)
    month = int(month)
    start_of_month = datetime.datetime(year, month, 1)
    start_of_next_month = first_day_of_next_month(year, month)
    start_of_previous_month = first_day_of_previous_month(year, month)
    logger.debug("corp_member_view called by user %s" % request.user)

    try:
        user_main = EveCharacter.objects.get(
            character_id=AuthServicesInfo.objects.get_or_create(user=request.user)[0].main_char_id)
        user_corp_id = user_main.corporation_id
    except (ValueError, EveCharacter.DoesNotExist):
        user_corp_id = settings.CORP_ID

    if not settings.IS_CORP:
        alliance = EveAllianceInfo.objects.get(alliance_id=settings.ALLIANCE_ID)
        alliancecorps = EveCorporationInfo.objects.filter(alliance=alliance)
        membercorplist = [(int(membercorp.corporation_id), str(membercorp.corporation_name)) for membercorp in
                          alliancecorps]
        membercorplist.sort(key=lambda tup: tup[1])
        membercorp_id_list = [int(membercorp.corporation_id) for membercorp in alliancecorps]

        bluecorps = EveCorporationInfo.objects.filter(is_blue=True)
        bluecorplist = [(int(bluecorp.corporation_id), str(bluecorp.corporation_name)) for bluecorp in bluecorps]
        bluecorplist.sort(key=lambda tup: tup[1])
        bluecorp_id_list = [int(bluecorp.corporation_id) for bluecorp in bluecorps]

        if not (user_corp_id in membercorp_id_list or user_corp_id not in bluecorp_id_list):
            user_corp_id = None

    if not corpid:
        if settings.IS_CORP:
            corpid = settings.CORP_ID
        elif user_corp_id:
            corpid = user_corp_id
        else:
            corpid = membercorplist[0][0]

    corp = EveCorporationInfo.objects.get(corporation_id=corpid)
    if request.user.has_perm('auth.alliance_apis') or (request.user.has_perm('auth.corp_apis') and user_corp_id == corpid):
        logger.debug("Retreiving and sending API-information")

        if settings.IS_CORP:
            try:
                member_list = EveApiManager.get_corp_membertracking(settings.CORP_API_ID, settings.CORP_API_VCODE)
            except APIError:
                logger.debug("Corp API does not have membertracking scope, using EveWho data instead.")
                member_list = EveWhoManager.get_corporation_members(corpid)
        else:
            member_list = EveWhoManager.get_corporation_members(corpid)

        characters_with_api = {}
        characters_without_api = {}

        num_registered_characters = 0
        for char_id, member_data in member_list.items():
            try:
                char = EveCharacter.objects.get(character_id=char_id)
                char_owner = char.user
                try:
                    mainid = int(AuthServicesInfo.objects.get_or_create(user=char_owner)[0].main_char_id)
                    mainchar = EveCharacter.objects.get(character_id=mainid)
                    mainname = mainchar.character_name
                    maincorp = mainchar.corporation_name
                    maincorpid = mainchar.corporation_id
                    api_pair = EveApiKeyPair.objects.get(api_id=char.api_id)
                except (ValueError, EveCharacter.DoesNotExist, EveApiKeyPair.DoesNotExist):
                    logger.info("No main character seem to be set for character %s" % char.character_name)
                    mainname = "User: " + char_owner.username
                    mainchar = char
                    maincorp = "Not set."
                    maincorpid = None
                    api_pair = None
                num_registered_characters += 1
                characters_with_api.setdefault(mainname, Player(main=mainchar,
                                                                user=char_owner,
                                                                maincorp=maincorp,
                                                                maincorpid=maincorpid,
                                                                altlist=[],
                                                                apilist=[],
                                                                n_fats=0)
                                               ).altlist.append(char)
                if api_pair:
                    characters_with_api[mainname].apilist.append(api_pair)

            except EveCharacter.DoesNotExist:
                characters_without_api.update({member_data["name"]: member_data["id"]})

        for char in EveCharacter.objects.filter(corporation_id=corpid):
            if not int(char.character_id) in member_list:
                logger.info("Character '%s' does not exist in EveWho dump." % char.character_name)
                char_owner = char.user
                try:
                    mainid = int(AuthServicesInfo.objects.get_or_create(user=char_owner)[0].main_char_id)
                    mainchar = EveCharacter.objects.get(character_id=mainid)
                    mainname = mainchar.character_name
                    maincorp = mainchar.corporation_name
                    maincorpid = mainchar.corporation_id
                    api_pair = EveApiKeyPair.objects.get(api_id=char.api_id)
                except (ValueError, EveCharacter.DoesNotExist, EveApiKeyPair.DoesNotExist):
                    logger.info("No main character seem to be set for character %s" % char.character_name)
                    mainname = "User: " + char_owner.username
                    mainchar = char
                    maincorp = "Not set."
                    maincorpid = None
                    api_pair = None
                num_registered_characters += 1
                characters_with_api.setdefault(mainname, Player(main=mainchar,
                                                                user=char_owner,
                                                                maincorp=maincorp,
                                                                maincorpid=maincorpid,
                                                                altlist=[],
                                                                apilist=[],
                                                                n_fats=0)
                                               ).altlist.append(char)
                if api_pair:
                    characters_with_api[mainname].apilist.append(api_pair)

        n_unacounted = corp.member_count - (num_registered_characters + len(characters_without_api))

        for mainname, player in characters_with_api.items():
            fats_this_month = Fat.objects.filter(user=player.user).filter(
                fatlink__fatdatetime__gte=start_of_month).filter(fatlink__fatdatetime__lt=start_of_next_month)
            characters_with_api[mainname].n_fats = len(fats_this_month)

        if start_of_next_month > datetime.datetime.now():
            start_of_next_month = None

        if not settings.IS_CORP:
            context = {"membercorplist": membercorplist,
                       "corp": corp,
                       "characters_with_api": sorted(characters_with_api.items()),
                       'n_registered': num_registered_characters,
                       'n_unacounted': n_unacounted,
                       "characters_without_api": sorted(characters_without_api.items()),
                       "search_form": CorputilsSearchForm()}
        else:
            logger.debug("corp_member_view running in corportation mode")
            context = {"corp": corp,
                       "characters_with_api": sorted(characters_with_api.items()),
                       'n_registered': num_registered_characters,
                       'n_unacounted': n_unacounted,
                       "characters_without_api": sorted(characters_without_api.items()),
                       "search_form": CorputilsSearchForm()}

        context["next_month"] = start_of_next_month
        context["previous_month"] = start_of_previous_month
        context["this_month"] = start_of_month

        return render(request, 'registered/corputils.html', context=context)
    else:
        logger.warn('User %s (%s) not authorized to view corp stats for corp id %s' % (request.user, user_corp_id, corpid))
    return redirect("auth_dashboard")

Example 12

Project: allianceauth
Source File: views.py
View license
@login_required
def corputils_search(request, corpid=settings.CORP_ID):
    logger.debug("corputils_search called by user %s" % request.user)

    corp = EveCorporationInfo.objects.get(corporation_id=corpid)

    authorized = False
    try:
        user_main = EveCharacter.objects.get(
            character_id=AuthServicesInfo.objects.get_or_create(user=request.user)[0].main_char_id)
        if request.user.has_perm('auth.alliance_apis') or (
                    request.user.has_perm('auth.corp_apis') and (user_main.corporation_id == corpid)):
            logger.debug("Retreiving and sending API-information")
            authorized = True
    except (ValueError, EveCharacter.DoesNotExist):
        if request.user.has_perm('auth.alliance_apis'):
            logger.debug("Retrieving and sending API-information")
            authorized = True

    if authorized:
        if request.method == 'POST':
            form = CorputilsSearchForm(request.POST)
            logger.debug("Request type POST contains form valid: %s" % form.is_valid())
            if form.is_valid():
                # Really dumb search and only checks character name
                # This can be improved but it does the job for now
                searchstring = form.cleaned_data['search_string']
                logger.debug("Searching for player with character name %s for user %s" % (searchstring, request.user))

                member_list = {}
                if settings.IS_CORP:
                    member_list = EveApiManager.get_corp_membertracking(settings.CORP_API_ID, settings.CORP_API_VCODE)
                if not member_list:
                    logger.debug('Unable to fetch members from API. Pulling from EveWho')
                    member_list = EveWhoManager.get_corporation_members(corpid)

                SearchResult = namedtuple('SearchResult',
                                          ['name', 'id', 'main', 'api_registered', 'character', 'apiinfo'])

                searchresults = []
                for memberid, member_data in member_list.items():
                    if searchstring.lower() in member_data["name"].lower():
                        try:
                            char = EveCharacter.objects.get(character_name=member_data["name"])
                            user = char.user
                            mainid = int(AuthServicesInfo.objects.get_or_create(user=user)[0].main_char_id)
                            main = EveCharacter.objects.get(character_id=mainid)
                            if can_see_api(request.user, char):
                                api_registered = True
                                apiinfo = EveApiKeyPair.objects.get(api_id=char.api_id)
                            else:
                                api_registered = False
                                apiinfo = None
                        except EveCharacter.DoesNotExist:
                            api_registered = False
                            char = None
                            main = ""
                            apiinfo = None

                        searchresults.append(SearchResult(name=member_data["name"], id=memberid, main=main,
                                                          api_registered=api_registered,
                                                          character=char, apiinfo=apiinfo))

                logger.info("Found %s members for user %s matching search string %s" % (
                    len(searchresults), request.user, searchstring))

                context = {'corp': corp, 'results': searchresults, 'search_form': CorputilsSearchForm(),
                           "year": datetime.datetime.now().year, "month": datetime.datetime.now().month}

                return render(request, 'registered/corputilssearchview.html',
                              context=context)
            else:
                logger.debug("Form invalid - returning for user %s to retry." % request.user)
                context = {'corp': corp, 'members': None, 'search_form': CorputilsSearchForm()}
                return render(request, 'registered/corputilssearchview.html', context=context)

        else:
            logger.debug("Returning empty search form for user %s" % request.user)
            return redirect("auth_corputils")
    else:
        logger.warn('User %s not authorized to view corp stats for corp ID %s' % (request.user, corpid))
    return redirect("auth_dashboard")

Example 13

Project: django-yarr
Source File: views.py
View license
@login_required
def list_entries(
    request, feed_pk=None, state=None, template="yarr/list_entries.html",
):
    """
    Display a list of entries
    Takes optional arguments to determine which entries to list:
        feed_pk     Primary key for a Feed
        state       The state of entries to list; one of:
                    None            All entries
                    ENTRY_UNREAD    Unread entries
                    ENTRY_SAVED     Saved entries

    Takes a single querystring argument:
        order       If "asc", order chronologically (otherwise
                    reverse-chronologically).

    Note: no built-in url calls this with state == ENTRY_READ, but support
    exists for a custom url.
    """
    # Get entries queryset
    qs, feed = get_entries(request, feed_pk, state)
    
    order = request.GET.get('order', ORDER_DESC)
    if order == ORDER_ASC:
        qs = qs.order_by('date')
    else:
        qs = qs.order_by('-date')

    # Make list of available pks for this page
    available_pks = list(qs.values_list('pk', flat=True))
    
    # Paginate
    entries, pagination = utils.paginate(request, qs)
    
    # Base title
    if state is None:
        title = 'All items'
    elif state == ENTRY_UNREAD:
        title = 'Unread items'
    elif state == ENTRY_SAVED:
        title = 'Saved items'
    else:
        raise ValueError('Cannot list entries in unknown state')
        
    # Add tag feed to title
    if feed:
        title = '%s - %s' % (feed.title, title)
    
    # Get list of feeds for feed list
    feeds = models.Feed.objects.filter(user=request.user)
    
    # Determine current view for reverse
    if state is None:
        current_view = 'yarr-list_all'
    elif state == ENTRY_UNREAD:
        current_view = 'yarr-list_unread'
    elif state == ENTRY_SAVED:
        current_view = 'yarr-list_saved'
    
    return render(request, template, {
        'title':    title,
        'entries':  entries,
        'pagination': pagination,
        'feed':     feed,
        'feeds':    feeds,
        'state':    state,
        'order_asc':    order == ORDER_ASC,
        'constants':    constants,
        'current_view': current_view,
        'yarr_settings': {
            'add_jquery':       settings.ADD_JQUERY,
            # JavaScript YARR_CONFIG variables
            'config':   utils.jsonEncode({
                'api':  reverse('yarr-api_base'),
                'con':  '#yarr_con',
                'initial_state':    state,
                'initial_order':    order,
                'initial_feed':     feed_pk,
                'layout_fixed':     settings.LAYOUT_FIXED,
                'api_page_length':  settings.API_PAGE_LENGTH,
                'title_template':   settings.TITLE_TEMPLATE,
                'title_selector':   settings.TITLE_SELECTOR,
                'available_pks':    available_pks,
                'url_all': {
                    None:           reverse('yarr-list_all'),
                    ENTRY_UNREAD:   reverse('yarr-list_unread'),
                    ENTRY_SAVED:    reverse('yarr-list_saved'),
                },
                'url_feed': {
                    None:           reverse('yarr-list_all', kwargs={'feed_pk':'00'}),
                    ENTRY_UNREAD:   reverse('yarr-list_unread', kwargs={'feed_pk':'00'}),
                    ENTRY_SAVED:    reverse('yarr-list_saved', kwargs={'feed_pk':'00'}),
                }
            }),
        },
    })

Example 14

Project: django-yarr
Source File: views.py
View license
@login_required
def entry_state(
    request, feed_pk=None, entry_pk=None, state=None, if_state=None,
    template="yarr/confirm.html",
):
    """
    Change entry state for an entry, a feed, or all entries
    """
    # Filter entries by selection
    qs = models.Entry.objects.user(request.user)
    if entry_pk is not None:
        # Changing specific entry
        qs = qs.filter(pk=entry_pk)
        
    elif state == ENTRY_READ:
        if feed_pk is not None:
            # Changing all entries in a feed
            qs = qs.filter(feed__pk=feed_pk)
            
        # Only mark unread as read - don't change saved
        qs = qs.unread()
        
    else:
        # Either unknown state, or trying to bulk unread/save
        messages.error(request, 'Cannot perform this operation')
        return HttpResponseRedirect(reverse(home))
        
    # Check for if_state
    if if_state is not None:
        if if_state == ENTRY_UNREAD:
            qs = qs.unread()
        elif if_state == ENTRY_READ:
            qs = qs.read()
        elif if_state == ENTRY_SAVED:
            qs = qs.saved()
        else:
            messages.error(request, 'Unknown condition')
            return HttpResponseRedirect(reverse(home))
        
    # Check there's something to change
    count = qs.count()
    if count == 0:
        messages.error(request, 'No entries found to change')
        return HttpResponseRedirect(reverse(home))
    
    # Process
    if request.POST:
        # Change state and update unread count
        qs.set_state(state)
        
        # If they're not marked as read, they can't ever expire
        # If they're marked as read, they will be given an expiry date
        # when Feed._update_entries determines they can expire
        if state != ENTRY_READ:
            qs.clear_expiry()
        
        if state is ENTRY_UNREAD:
            messages.success(request, 'Marked as unread')
        elif state is ENTRY_READ:
            messages.success(request, 'Marked as read')
        elif state is ENTRY_SAVED:
            messages.success(request, 'Saved')
        return HttpResponseRedirect(reverse(home))
    
    # Prep messages
    op_text = {
        'verb': 'mark',
        'desc': '',
    }
    if state is ENTRY_UNREAD:
        op_text['desc'] = ' as unread'
    elif state is ENTRY_READ:
        op_text['desc'] = ' as read'
    elif state is ENTRY_SAVED:
        op_text['verb'] = 'save'
        
    if entry_pk:
        title = '%(verb)s item%(desc)s'
        msg = 'Are you sure you want to %(verb)s this item%(desc)s?'
    elif feed_pk:
        title = '%(verb)s feed%(desc)s'
        msg = 'Are you sure you want to %(verb)s all items in the feed%(desc)s?'
    else:
        title = '%(verb)s all items%(desc)s'
        msg = 'Are you sure you want to %(verb)s all items in every feed%(desc)s?'
    
    title = title % op_text
    title = title[0].upper() + title[1:]
    
    return render(request, template, {
        'title':    title,
        'message':  msg % op_text,
        'submit_label': title,
    })

Example 15

Project: Resmin
Source File: views.py
View license
@delete_notification
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 = \
            request.user.has_pending_follow_request(user)


    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 = Story.objects.build(
            frm=user, requested_user=request.user, listing=listing)
        ctx['stories'] = paginated(request, stories,
                                   settings.STORIES_PER_PAGE)
    if request.POST:
        question_form = QuestionForm(request.POST, questioner=request.user,
                                     questionee=user)
        if question_form.is_valid():
            question_form.save()
            messages.success(request, _('Your question sent to user.'))
            return HttpResponseRedirect(user.get_absolute_url())
    else:
        question_form = QuestionForm(questioner=request.user,
                                     questionee=user)

    if action:
        ctx['action'] = action
        follow_form = FollowForm(follower=request.user,
                                 target=user,
                                 action=action)
        if request.POST:
            follow_form = FollowForm(request.POST,
                                     follower=request.user,
                                     target=user,
                                     action=action)
            if follow_form.is_valid():
                follow_form.save()
                if action == 'follow':
                    messages.success(
                        request, _('Follow request sent to user'))
                elif action == 'unfollow':
                    messages.success(
                        request, _('You are not a follower anymore'))
                elif action == 'block':
                    messages.success(
                        request, _('You have blocked this user'))
                elif action == 'unblock':
                    messages.success(
                        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 16

Project: wagtailplus
Source File: views.py
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        = revision.page

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

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

    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:
            new_revision.publish()

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

        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(
        request,
        template_name,
        {
            'page':         page,
            'revision':     revision,
            'page_perms':   page_perms
        }
    )

Example 17

Project: satnogs-network
Source File: views.py
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()

    try:
        satellites = Satellite.objects.filter(transmitters__alive=True).distinct()
    except:
        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)
    observer.lat = str(station.lat)
    observer.elevation = station.alt

    nextpasses = []
    passid = 0

    for satellite in satellites:
        observer.date = ephem.date(datetime.today())

        try:
            sat_ephem = ephem.readtle(str(satellite.latest_tle.tle0),
                                      str(satellite.latest_tle.tle1),
                                      str(satellite.latest_tle.tle2))

            # 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:
                try:
                    tr, azr, tt, altt, ts, azs = observer.next_pass(sat_ephem)

                    if tr is None:
                        break

                    # 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:
                        pass

                    # 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 < ephem.date(datetime.today() + timedelta(hours=6)):
                        if float(elevation) >= station.horizon:
                            sat_pass = {'passid': passid,
                                        'mytime': str(observer.date),
                                        'debug': observer.next_pass(sat_ephem),
                                        'name': str(satellite.name),
                                        'id': str(satellite.id),
                                        '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
                            nextpasses.append(sat_pass)
                        observer.date = ephem.Date(ts).datetime() + timedelta(minutes=1)
                        continue
                    else:
                        keep_digging = False
                    continue
                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:
                    break
        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 18

Project: django-adminactions
Source File: mass_update.py
View license
def mass_update(modeladmin, request, queryset):  # noqa
    """
        mass update queryset
    """

    def not_required(field, **kwargs):
        """ force all fields as not required"""
        kwargs['required'] = False
        return field.formfield(**kwargs)

    def _doit():
        errors = {}
        updated = 0
        for record in queryset:
            for field_name, value_or_func in list(form.cleaned_data.items()):
                if callable(value_or_func):
                    old_value = getattr(record, field_name)
                    setattr(record, field_name, value_or_func(old_value))
                else:
                    setattr(record, field_name, value_or_func)
            if clean:
                record.clean()
            record.save()
            updated += 1
        if updated:
            messages.info(request, _("Updated %s records") % updated)

        if len(errors):
            messages.error(request, "%s records not updated due errors" % len(errors))
        adminaction_end.send(sender=modeladmin.model,
                             action='mass_update',
                             request=request,
                             queryset=queryset,
                             modeladmin=modeladmin,
                             form=form,
                             errors=errors,
                             updated=updated)

    opts = modeladmin.model._meta
    perm = "{0}.{1}".format(opts.app_label, get_permission_codename('adminactions_massupdate', opts))
    if not request.user.has_perm(perm):
        messages.error(request, _('Sorry you do not have rights to execute this action'))
        return

    try:
        adminaction_requested.send(sender=modeladmin.model,
                                   action='mass_update',
                                   request=request,
                                   queryset=queryset,
                                   modeladmin=modeladmin)
    except ActionInterrupted as e:
        messages.error(request, str(e))
        return

    # Allows to specified a custom mass update Form in the ModelAdmin
    mass_update_form = getattr(modeladmin, 'mass_update_form', MassUpdateForm)

    MForm = modelform_factory(modeladmin.model, form=mass_update_form,
                              exclude=('pk',),
                              formfield_callback=not_required)
    grouped = defaultdict(lambda: [])
    selected_fields = []
    initial = {'_selected_action': request.POST.getlist(helpers.ACTION_CHECKBOX_NAME),
               'select_across': request.POST.get('select_across') == '1',
               'action': 'mass_update'}

    if 'apply' in request.POST:
        form = MForm(request.POST)
        if form.is_valid():
            try:
                adminaction_start.send(sender=modeladmin.model,
                                       action='mass_update',
                                       request=request,
                                       queryset=queryset,
                                       modeladmin=modeladmin,
                                       form=form)
            except ActionInterrupted as e:
                messages.error(request, str(e))
                return HttpResponseRedirect(request.get_full_path())

            # need_transaction = form.cleaned_data.get('_unique_transaction', False)
            validate = form.cleaned_data.get('_validate', False)
            clean = form.cleaned_data.get('_clean', False)

            if validate:
                with compat.atomic():
                    _doit()

            else:
                values = {}
                for field_name, value in list(form.cleaned_data.items()):
                    if isinstance(form.fields[field_name], ModelMultipleChoiceField):
                        messages.error(request, "Unable no mass update ManyToManyField without 'validate'")
                        return HttpResponseRedirect(request.get_full_path())
                    elif callable(value):
                        messages.error(request, "Unable no mass update using operators without 'validate'")
                        return HttpResponseRedirect(request.get_full_path())
                    elif field_name not in ['_selected_action', '_validate', 'select_across', 'action',
                                            '_unique_transaction', '_clean']:
                        values[field_name] = value
                queryset.update(**values)

            return HttpResponseRedirect(request.get_full_path())
    else:
        initial.update({'action': 'mass_update', '_validate': 1})
        # form = MForm(initial=initial)
        prefill_with = request.POST.get('prefill-with', None)
        prefill_instance = None
        try:
            # Gets the instance directly from the queryset for data security
            prefill_instance = queryset.get(pk=prefill_with)
        except ObjectDoesNotExist:
            pass

        form = MForm(initial=initial, instance=prefill_instance)

    for el in queryset.all()[:10]:
        for f in modeladmin.model._meta.fields:
            if f.name not in form._no_sample_for:
                if hasattr(f, 'flatchoices') and f.flatchoices:
                    grouped[f.name] = list(dict(getattr(f, 'flatchoices')).values())
                elif hasattr(f, 'choices') and f.choices:
                    grouped[f.name] = list(dict(getattr(f, 'choices')).values())
                elif isinstance(f, df.BooleanField):
                    grouped[f.name] = [True, False]
                else:
                    value = getattr(el, f.name)
                    if value is not None and value not in grouped[f.name]:
                        grouped[f.name].append(value)
                    initial[f.name] = initial.get(f.name, value)

    adminForm = helpers.AdminForm(form, modeladmin.get_fieldsets(request), {}, [], model_admin=modeladmin)
    media = modeladmin.media + adminForm.media
    dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.date) else str(obj)
    tpl = 'adminactions/mass_update.html'
    ctx = {'adminform': adminForm,
           'form': form,
           'action_short_description': mass_update.short_description,
           'title': u"%s (%s)" % (
               mass_update.short_description.capitalize(),
               smart_text(modeladmin.opts.verbose_name_plural),
           ),
           'grouped': grouped,
           'fieldvalues': json.dumps(grouped, default=dthandler),
           'change': True,
           'selected_fields': selected_fields,
           'is_popup': False,
           'save_as': False,
           'has_delete_permission': False,
           'has_add_permission': False,
           'has_change_permission': True,
           'opts': modeladmin.model._meta,
           'app_label': modeladmin.model._meta.app_label,
           # 'action': 'mass_update',
           # 'select_across': request.POST.get('select_across')=='1',
           'media': mark_safe(media),
           'selection': queryset}
    if django.VERSION[:2] > (1, 7):
        ctx.update(modeladmin.admin_site.each_context(request))
    else:
        ctx.update(modeladmin.admin_site.each_context())

    if django.VERSION[:2] > (1, 8):
        return render(request, tpl, context=ctx)
    else:
        return render_to_response(tpl, RequestContext(request, ctx))

Example 19

Project: django-adminactions
Source File: merge.py
View license
def merge(modeladmin, request, queryset):  # noqa
    """
    Merge two model instances. Move all foreign keys.

    """

    opts = modeladmin.model._meta
    perm = "{0}.{1}".format(opts.app_label, get_permission_codename('adminactions_merge', opts))
    if not request.user.has_perm(perm):
        messages.error(request, _('Sorry you do not have rights to execute this action'))
        return

    def raw_widget(field, **kwargs):
        """ force all fields as not required"""
        kwargs['widget'] = TextInput({'class': 'raw-value'})
        return field.formfield(**kwargs)

    merge_form = getattr(modeladmin, 'merge_form', MergeForm)
    MForm = modelform_factory(modeladmin.model,
                              form=merge_form,
                              exclude=('pk', ),
                              formfield_callback=raw_widget)
    OForm = modelform_factory(modeladmin.model,
                              exclude=('pk', ),
                              formfield_callback=raw_widget)

    tpl = 'adminactions/merge.html'
    # transaction_supported = model_supports_transactions(modeladmin.model)
    ctx = {
        '_selected_action': request.POST.getlist(helpers.ACTION_CHECKBOX_NAME),
        'transaction_supported': 'Un',
        'select_across': request.POST.get('select_across') == '1',
        'action': request.POST.get('action'),
        'fields': [f for f in queryset.model._meta.fields if not f.primary_key and f.editable],
        'app_label': queryset.model._meta.app_label,
        'result': '',
        'opts': queryset.model._meta}

    if 'preview' in request.POST:
        master = queryset.get(pk=request.POST.get('master_pk'))
        original = clone_instance(master)
        other = queryset.get(pk=request.POST.get('other_pk'))
        formset = formset_factory(OForm)(initial=[model_to_dict(master), model_to_dict(other)])
        with transaction.nocommit():
            form = MForm(request.POST, instance=master)
            other.delete()
            form_is_valid = form.is_valid()
        if form_is_valid:
            ctx.update({'original': original})
            tpl = 'adminactions/merge_preview.html'
        else:
            master = queryset.get(pk=request.POST.get('master_pk'))
            other = queryset.get(pk=request.POST.get('other_pk'))

    elif 'apply' in request.POST:
        master = queryset.get(pk=request.POST.get('master_pk'))
        other = queryset.get(pk=request.POST.get('other_pk'))
        formset = formset_factory(OForm)(initial=[model_to_dict(master), model_to_dict(other)])
        with transaction.nocommit():
            form = MForm(request.POST, instance=master)
            stored_pk = other.pk
            other.delete()
            ok = form.is_valid()
            other.pk = stored_pk
        if ok:
            if form.cleaned_data['dependencies'] == MergeForm.DEP_MOVE:
                related = api.ALL_FIELDS
            else:
                related = None
            fields = form.cleaned_data['field_names']
            api.merge(master, other, fields=fields, commit=True, related=related)
            return HttpResponseRedirect(request.path)
        else:
            messages.error(request, form.errors)
    else:
        try:
            master, other = queryset.all()
            # django 1.4 need to remove the trailing milliseconds
            for field in master._meta.fields:
                if isinstance(field, models.DateTimeField):
                    for target in (master, other):
                        raw_value = getattr(target, field.name)
                        if raw_value:
                            fixed_value = datetime(
                                raw_value.year,
                                raw_value.month,
                                raw_value.day,
                                raw_value.hour,
                                raw_value.minute,
                                raw_value.second)
                            setattr(target, field.name, fixed_value)
        except ValueError:
            messages.error(request, _('Please select exactly 2 records'))
            return

        initial = {'_selected_action': request.POST.getlist(helpers.ACTION_CHECKBOX_NAME),
                   'select_across': 0,
                   'generic': MergeForm.GEN_IGNORE,
                   'dependencies': MergeForm.DEP_MOVE,
                   'action': 'merge',
                   'master_pk': master.pk,
                   'other_pk': other.pk}
        formset = formset_factory(OForm)(initial=[model_to_dict(master), model_to_dict(other)])
        form = MForm(initial=initial, instance=master)

    adminForm = helpers.AdminForm(form, modeladmin.get_fieldsets(request), {}, [], model_admin=modeladmin)
    media = modeladmin.media + adminForm.media
    ctx.update({'adminform': adminForm,
                'formset': formset,
                'media': mark_safe(media),
                'action_short_description': merge.short_description,
                'title': u"%s (%s)" % (
                    merge.short_description.capitalize(),
                    smart_text(modeladmin.opts.verbose_name_plural),
                ),
                'master': master,
                'other': other})
    if django.VERSION[:2] > (1, 7):
        ctx.update(modeladmin.admin_site.each_context(request))
    else:
        ctx.update(modeladmin.admin_site.each_context())
    if django.VERSION[:2] > (1, 8):
        return render(request, tpl, context=ctx)
    else:
        return render_to_response(tpl, RequestContext(request, ctx))

Example 20

Project: django-filebrowser
Source File: sites.py
View license
    def browse(self, request):
        "Browse Files/Directories."
        filter_re = []
        for exp in EXCLUDE:
            filter_re.append(re.compile(exp))

        # do not filter if VERSIONS_BASEDIR is being used
        if not VERSIONS_BASEDIR:
            for k, v in VERSIONS.items():
                exp = (r'_%s(%s)$') % (k, '|'.join(EXTENSION_LIST))
                filter_re.append(re.compile(exp, re.IGNORECASE))

        def filter_browse(item):
            "Defining a browse filter"
            filtered = item.filename.startswith('.')
            for re_prefix in filter_re:
                if re_prefix.search(item.filename):
                    filtered = True
            if filtered:
                return False
            return True

        query = request.GET.copy()
        path = u'%s' % os.path.join(self.directory, query.get('dir', ''))

        filelisting = self.filelisting_class(
            path,
            filter_func=filter_browse,
            sorting_by=query.get('o', DEFAULT_SORTING_BY),
            sorting_order=query.get('ot', DEFAULT_SORTING_ORDER),
            site=self)

        files = []
        if SEARCH_TRAVERSE and query.get("q"):
            listing = filelisting.files_walk_filtered()
        else:
            listing = filelisting.files_listing_filtered()

        # If we do a search, precompile the search pattern now
        do_search = query.get("q")
        if do_search:
            re_q = re.compile(query.get("q").lower(), re.M)

        filter_type = query.get('filter_type')
        filter_date = query.get('filter_date')

        for fileobject in listing:
            # date/type filter
            append = False
            if (not filter_type or fileobject.filetype == filter_type) and (not filter_date or get_filterdate(filter_date, fileobject.date or 0)):
                append = True
            # search
            if do_search and not re_q.search(fileobject.filename.lower()):
                append = False
            # append
            if append:
                files.append(fileobject)

        filelisting.results_total = len(listing)
        filelisting.results_current = len(files)

        p = Paginator(files, LIST_PER_PAGE)
        page_nr = request.GET.get('p', '1')
        try:
            page = p.page(page_nr)
        except (EmptyPage, InvalidPage):
            page = p.page(p.num_pages)

        request.current_app = self.name
        return render(request, 'filebrowser/index.html', {
            'p': p,
            'page': page,
            'filelisting': filelisting,
            'query': query,
            'title': _(u'FileBrowser'),
            'settings_var': get_settings_var(directory=self.directory),
            'breadcrumbs': get_breadcrumbs(query, query.get('dir', '')),
            'breadcrumbs_title': "",
            'filebrowser_site': self
        })

Example 21

Project: coursys
Source File: financials.py
View license
@login_required
def financials(request, grad_slug, style='complete'):
    if style not in STYLES:
        return NotFoundResponse(request)

    grad, _, units = _can_view_student(request, grad_slug, funding=True)
    if grad is None:
        return ForbiddenResponse(request)

    current_status = GradStatus.objects.filter(student=grad, hidden=False).order_by('-start')[0]
    grad_status_qs = GradStatus.objects.filter(student=grad, hidden=False, status__in=STATUS_ACTIVE).select_related('start','end')
    scholarships_qs = Scholarship.objects.filter(student=grad, removed=False).select_related('start_semester','end_semester')
    promises_qs = Promise.objects.filter(student=grad, removed=False).select_related('start_semester','end_semester')
    other_fundings = OtherFunding.objects.filter(student=grad, removed=False).select_related('semester')
    
    contracts = TAContract.objects.filter(application__person=grad.person).exclude(status__in=STATUSES_NOT_TAING).select_related('posting__semester')
    other_contracts = NewTAContract.objects.filter(person=grad.person, status__in=['NEW', 'SGN'])\
                    .select_related('category')\
                    .prefetch_related('course')
    appointments = RAAppointment.objects.filter(person=grad.person, deleted=False)
    program_history = GradProgramHistory.objects.filter(student=grad).select_related('start_semester', 'program')
    financial_comments = FinancialComment.objects.filter(student=grad, removed=False).select_related('semester')
    
    # initialize earliest starting and latest ending semesters for display. 
    # Falls back on current semester if none 
    all_semesters = itertools.chain( # every semester we have info for
                      (s.start for s in grad_status_qs),
                      (s.end for s in grad_status_qs),
                      (p.start_semester for p in promises_qs),
                      (p.end_semester for p in promises_qs),
                      (s.start_semester for s in scholarships_qs),
                      (s.end_semester for s in scholarships_qs),
                      (o.semester for o in other_fundings),
                      (c.posting.semester for c in contracts),
                      (c.semester for c in financial_comments),
                      (get_semester(a.start_date) for a in appointments),
                      (get_semester(a.end_date) for a in appointments),
                      (ph.start_semester for ph in program_history),
                    )
    all_semesters = itertools.ifilter(lambda x: isinstance(x, Semester), all_semesters)
    all_semesters = set(all_semesters)
    if len(all_semesters) == 0:
        all_semesters = [get_semester()]
    earliest_semester = min(all_semesters)
    latest_semester = max(all_semesters)

    semesters = []
    semesters_qs = Semester.objects.filter(start__gte=earliest_semester.start, end__lte=latest_semester.end).order_by('-start')
    current_acad_year = None

    # build data structure with funding for each semester
    for semester in semesters_qs:
        semester_total = decimal.Decimal(0)

        yearpos = (semester - grad.start_semester) % 3 # position in academic year: 0 is start of a new academic year for this student
        if not current_acad_year or yearpos == 2:
            # keep this (mutable) structure that we can alias in each semester and keep running totals
            current_acad_year = {'total': 0, 'semcount': 0, 'endsem': semester}

        # other funding
        other_funding = other_fundings.filter(semester=semester)
        other_total = 0
        for other in other_funding:
            if other.eligible:
                other_total += other.amount
                semester_total += other.amount
        
        # scholarships
        semester_scholarships = scholarships_qs.filter(start_semester__name__lte=semester.name, end_semester__name__gte=semester.name)
        semester_eligible_scholarships = semester_scholarships.filter(scholarship_type__eligible=True)
        scholarships = []

        scholarship_total = 0
        for ss in semester_scholarships:
            amt = ss.amount/(ss.end_semester-ss.start_semester+1)
            scholarship_total += amt
            scholarships.append({'scholarship': ss, 'semester_amount': amt})

        for semester_eligible_scholarship in semester_eligible_scholarships:
            if(semester_eligible_scholarship.start_semester != semester_eligible_scholarship.end_semester):
                semester_span = semester_eligible_scholarship.end_semester - semester_eligible_scholarship.start_semester + 1
                semester_total += semester_eligible_scholarship.amount/semester_span
            else:
                semester_total += semester_eligible_scholarship.amount

        # grad status        
        status = None
        status_short = None
        for s in GradStatus.objects.filter(student=grad, hidden=False):
            if s.start <= semester and (s.end == None or semester <= s.end) :
                status = s.get_status_display()
                status_short = s.get_short_status_display()
        
        # grad program
        program = None
        for ph in program_history:
            if ph.start_semester == semester:
                program = ph
        
        # financial comments
        comments = []
        for c in financial_comments:
            if c.semester == semester:
                comments.append(c)
        
        # TAs
        ta_total = 0
        courses = []
        for contract in contracts:
            if contract.posting.semester == semester:
                for course in TACourse.objects.filter(contract=contract).exclude(bu=0).select_related('course'):
                    ta_total += course.pay()
                    if contract.status == 'SGN':
                        text = "%s (%s BU)" % (course.course.name(), course.total_bu)
                    else:
                        text = "%s (%s BU, current status: %s)" \
                             % (course.course.name(), course.total_bu, contract.get_status_display().lower())
                    courses.append({'course': text,'amount': course.pay()})
        for contract in other_contracts:
            if contract.category.hiring_semester.semester == semester:
                if contract.status == 'SGN':
                    for course in contract.course.all():
                        ta_total += course.total
                        courses.append({'course': "%s (%s BU)" % (course.course.name(), course.total_bu),
                                        'amount': course.total })
                else:
                    for course in contract.course.all():
                        courses.append({'course': "%s (%s BU - $%.02f) - Draft" % (course.course.name(), course.total_bu, course.total),
                                        'amount': 0 })
        ta = {'courses':courses,'amount':ta_total}
        semester_total += ta_total

        # RAs
        ra_total = 0
        appt = []
        for appointment in appointments:
            app_start_sem = appointment.start_semester()
            app_end_sem = appointment.end_semester()
            length = appointment.semester_length()
            if app_start_sem <= semester and app_end_sem >= semester:
                sem_pay = appointment.lump_sum_pay/length
                ra_total += sem_pay
                appt.append({'desc':"RA for %s - %s" % (appointment.hiring_faculty.name(), appointment.project),
                             'amount':sem_pay, 'semesters': appointment.semester_length() })
        ra = {'appt':appt, 'amount':ra_total}
        semester_total += ra_total
        
        # promises (ending in this semester, so we display them in the right spot)
        try:
            promise = promises_qs.filter(end_semester=semester)[0]
        except IndexError:
            promise = None
        
        current_acad_year['total'] += semester_total
        current_acad_year['semcount'] += 1
        semester_data = {'semester':semester, 'status':status, 'status_short': status_short, 'scholarships': scholarships,
                         'promise': promise, 'semester_total': semester_total, 'comments': comments,
                         'ta': ta, 'ra': ra, 'other_funding': other_funding, 'program': program,
                         'other_total': other_total, 'scholarship_total': scholarship_total,
                         'ta_total': ta_total, 'ra_total': ra_total, 'acad_year': current_acad_year}
        semesters.append(semester_data)

    promises = []
    for promise in promises_qs:
        received = decimal.Decimal(0)
        for semester in semesters:
            if semester['semester'] < promise.start_semester or semester['semester'] > promise.end_semester:
                continue
            received += semester['semester_total']
        
        owing = received - promise.amount
        # minor logic for display. 
        if owing < 0:
            owing = abs(owing)
        else:
            owing = -1
        
        # annotate the semester where we're displaying the promise with relevant info
        for semester in semesters:
            if semester['semester'] == promise.end_semester:
                semester['promisereceived'] = received
                semester['promiseowing'] = owing

    totals = {'ta': 0, 'ra': 0, 'scholarship': 0, 'other': 0, 'total': 0}
    for s in semesters:
        totals['ta'] += s['ta_total']
        totals['ra'] += s['ra_total']
        totals['scholarship'] += s['scholarship_total']
        totals['other'] += s['other_total']
        totals['total'] += s['semester_total']


    context = {
               'semesters': semesters,
               'promises': promises,
               'grad':grad,
               'status': current_status,
               'unit': units,
               'totals': totals,
               }
    return render(request, 'grad/view_financials-%s.html' % (style), context)

Example 22

Project: coursys
Source File: search.py
View license
@requires_role("GRAD", get_only=["GRPD"])
def search(request):
    current_user = Person.objects.get(userid=request.user.username)
    query_string = request.META.get('QUERY_STRING','')
    savedsearches = SavedSearch.objects.filter(person=current_user, query=query_string)
    if savedsearches:
        savedsearch = savedsearches[0]
    else:
        savedsearch = None

    form = SearchForm(initial={'student_status': STATUS_ACTIVE}) if len(request.GET) == 0 else SearchForm(request.GET)

    requirement_choices = [(r['series'], r['description']) for r in
            GradRequirement.objects.filter(program__unit__in=request.units, hidden=False)
            .order_by('description').values('series', 'description').distinct()]

    scholarshiptype_choices = [(st.id, st.name) for st in ScholarshipType.objects.filter(unit__in=request.units, hidden=False)]

    # If the user has the grad role for more than one unit, append the unit label to the name of the program so
    # they know which one they are looking at.
    if len(request.units) > 1:
        program_choices = [(gp.id, "%s - %s" % (gp.unit.label, gp.label)) for gp in
                           GradProgram.objects.filter(unit__in=request.units, hidden=False)]
    else:
        program_choices = [(gp.id, gp.label) for gp in GradProgram.objects.filter(unit__in=request.units, hidden=False)]

    status_choices = [(st,desc) for st,desc in STATUS_CHOICES if st not in STATUS_OBSOLETE] + [('', 'None')]

    supervisors = Supervisor.objects.filter(student__program__unit__in=request.units, supervisor_type='SEN',
                                            removed=False).select_related('supervisor')
    supervisors = set((s.supervisor for s in supervisors if s.supervisor))
    supervisors = list(supervisors)
    supervisors.sort()
    supervisor_choices = [(p.id, p.sortname()) for p in supervisors]

    grad_flags = GradFlag.objects.filter(unit__in=request.units)
    grad_flag_choices = [(g.id, g.label) for g in grad_flags]

    form.fields['requirements'].choices = requirement_choices
    form.fields['incomplete_requirements'].choices = requirement_choices
    form.fields['scholarshiptype'].choices = scholarshiptype_choices
    form.fields['program'].choices = program_choices
    form.fields['student_status'].choices = status_choices
    form.fields['supervisor'].choices = supervisor_choices
    form.fields['grad_flags'].choices = grad_flag_choices
    
    if 'sort' in request.GET:
        sort = _parse_sort(request.GET['sort'])
    else:
        sort = None;
    
    if 'edit_search' not in request.GET and form.is_valid():
        grads = form.search_results(request.units)

        overflow = False
        if len(grads) > MAX_RESULTS:
            grads = grads[:MAX_RESULTS]
            overflow = True
        
        if savedsearch is not None:
            saveform = SaveSearchForm(instance=savedsearch)
        else:
            saveform = SaveSearchForm(initial={'person':current_user, 'query':query_string})
        
        columns = form.cleaned_data['columns']
        # Here, we're using a nested list comprehension to convert column ids into column names - 
        #  for example 'person.first_name' into 'First Name' - using the COLUMN_CHOICES table provided in forms.py
        human_readable_column_headers = [[v[1] for _,v in enumerate(COLUMN_CHOICES) if v[0] == column][0] for column in columns]
        
        if 'csv' in request.GET:
            # CSV output
            response = HttpResponse(content_type='text/csv')
            response['Content-Disposition'] = 'inline; filename="grad_search.csv"'
            _generate_csv(response, columns, human_readable_column_headers, grads)
            return response
        
        elif 'excel' in request.GET:
            # Excel output
            response = HttpResponse(content_type='application/vnd.ms-excel')
            response['Content-Disposition'] = 'inline; filename="grad_search.xls"'
            _generate_excel(response, columns, human_readable_column_headers, grads)
            return response
        
        elif 'cardforms' in request.GET:
            # access card requisition output
            response = HttpResponse(content_type='application/pdf')
            response['Content-Disposition'] = 'inline; filename="card_access.pdf"'
            card_req_forms(grads, response)
            return response
        
        elif 'fasnetforms' in request.GET:
            # access card requisition output
            response = HttpResponse(content_type='application/pdf')
            response['Content-Disposition'] = 'inline; filename="fasnet_access.pdf"'
            fasnet_forms(grads, response)
            return response
        
        if overflow:
            messages.warning(request, "Too many result found: limited to %i." % (MAX_RESULTS))

        context = {
                   'grads': grads,
                   'human_readable_column_headers': human_readable_column_headers,
                   'columns': columns,
                   'saveform' : saveform,
                   'query_string': query_string,
                   'sort': sort,
                   'uses_fasnet': any(u.uses_fasnet() for u in request.units),
                   }
        resp = render(request, 'grad/search_results.html', context)
        return resp
    else:
        #savedsearches = SavedSearch.objects.filter(person__in=(current_user,None))
        page_title = 'Graduate Student Advanced Search'
        context = {
                   #'savedsearches' : savedsearches,
                   'page_title' : page_title,
                   'form':form,
                   'savedsearch' : savedsearch,
                   # a non-None savedsearch here means that somehow, an invalid search got saved
                   # the template gives the user the option to delete it
                   }
        resp = render(request, 'grad/search.html', context)
        return resp

Example 23

Project: coursys
Source File: view.py
View license
@login_required
def view(request, grad_slug, section=None):
    grad, authtype, units = _can_view_student(request, grad_slug)
    if grad is None or authtype == 'student':
        return ForbiddenResponse(request)

    # uses of the cortez link routed through here to see if they're actually being used
    if 'cortez-bounce' in request.GET and 'cortezid' in grad.config:
        from log.models import LogEntry
        from django.shortcuts import redirect
        l = LogEntry(userid=request.user.username,
              description="used cortez link for %s" % (grad.slug,),
              related_object=grad )
        l.save()
        return redirect("https://cortez.cs.sfu.ca/grad/scripts/grabcurrent.asp?Identifier=" + grad.config['cortezid'])
    
    context = {
        'grad': grad, 
        'index': True, 
        'can_edit': True, 
        'authtype': authtype }

    if authtype in ['supervisor', 'graddir']:
        context['can_edit'] = False
    
    for s in all_sections:
        context[s+'_content'] = ''
    
    if 'section' in request.GET:
        # page sections fetched by AJAX calls
        section = request.GET['section']

    if section:
        if section not in all_sections:
            return NotFoundResponse(request)
        
        elif section == 'general':
            programhistory = GradProgramHistory.objects.filter(student=grad, program__unit__in=units).order_by('starting')
            context['programhistory'] = programhistory
            flag_values = grad.flags_and_values()
            context['extras'] = [ (title, grad.config[field]) for field, title in grad.tacked_on_fields if field in grad.config] 
            context['flag_values'] = flag_values
            return render(request, 'grad/view__general.html', context)

        elif section == 'supervisors':
            supervisors = Supervisor.objects.filter(student=grad, removed=False).select_related('supervisor')
            context['supervisors'] = supervisors
            return render(request, 'grad/view__supervisors.html', context)

        elif section == 'status':
            statuses = GradStatus.objects.filter(student=grad, hidden=False).order_by('start__name')
            context['statuses'] = statuses
            return render(request, 'grad/view__status.html', context)

        elif section == 'requirements':
            completed_req = CompletedRequirement.objects.filter(student=grad, removed=False)
            completed_gradreq_id = [cr.requirement_id for cr in completed_req if cr.removed==False]
            req = GradRequirement.objects.filter(program=grad.program, hidden=False)
            missing_req = req.exclude(id__in=completed_gradreq_id)
            context['completed_req'] = completed_req
            context['missing_req'] = missing_req
            return render(request, 'grad/view__requirements.html', context)

        elif section == 'scholarships':
            scholarships = Scholarship.objects.filter(student=grad, removed=False).select_related('scholarship_type').order_by('start_semester__name')
            comments = FinancialComment.objects.filter(student=grad, comment_type='SCO', removed=False).order_by('created_at')
            context['scholarships'] = scholarships
            context['scholarship_comments'] = comments
            return render(request, 'grad/view__scholarships.html', context)

        elif section == 'otherfunding':
            otherfunding = OtherFunding.objects.filter(student=grad, removed=False).order_by('semester__name')
            context['otherfunding'] = otherfunding
            return render(request, 'grad/view__otherfunding.html', context)

        elif section == 'promises':
            promises = Promise.objects.filter(student=grad, removed=False).order_by('start_semester__name')
            context['promises'] = promises
            return render(request, 'grad/view__promises.html', context)

        elif section == 'tacontracts':
            tacontracts = TAContract.objects.filter(person=grad.person, status__in=['NEW', 'SGN'])
            oldcontracts = OldTAContract.objects.filter(application__person=grad.person)
            context['tacontracts'] = tacontracts
            context['oldcontracts'] = oldcontracts
            return render(request, 'grad/view__tacontracts.html', context)
        
        elif section == 'financialcomments':
            comments = FinancialComment.objects.filter(student=grad, removed=False).order_by('created_at')
            context['financial_comments'] = comments
            return render(request, 'grad/view__financialcomments.html', context)
        
        elif section == 'letters':
            letters = Letter.objects.filter(student=grad).select_related('template').order_by('date')
            context['letters'] = letters
            return render(request, 'grad/view__letters.html', context)
        
        elif section == 'progressreports':
            progressreports = ProgressReport.objects.filter(student=grad, 
                                                            removed=False)\
                                                            .order_by('date')
            context['progress_reports'] = progressreports
            return render(request, 'grad/view__progress.html', context)
        
        elif section == 'documents':
            documents = ExternalDocument.objects.filter(student=grad, 
                                                        removed=False)\
                                                        .order_by('date')
            context['documents'] = documents
            return render(request, 'grad/view__documents.html', context)

        elif section == 'visas':
            visas = Visa.get_visas([grad.person])
            context['visas'] = visas
            return render(request, 'grad/view__visas.html', context)

        else:
            raise ValueError, "Not all sections handled by view code: " + repr(section)

    elif '_escaped_fragment_' in request.GET:
        # Implement google-suggested hash-bang workaround. Not terribly efficient, but probably uncommon.
        # https://developers.google.com/webmasters/ajax-crawling/docs/getting-started
        sections = request.GET['_escaped_fragment_'].split(',')
        for s in sections:
            resp = view(request, grad_slug, section=s)
            context[s+'_content'] = mark_safe(resp.content)

    other_grad = GradStudent.objects \
                 .filter(program__unit__in=units, person=grad.person) \
                 .exclude(id=grad.id)
    other_applicant = [x for x in other_grad if x.is_applicant()]
    other_grad = [x for x in other_grad if not x.is_applicant()]
    context['other_grad'] = other_grad
    context['other_applicant'] = other_applicant

    return render(request, 'grad/view.html', context)

Example 24

Project: coursys
Source File: views.py
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
        else:
            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
        else:
            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 = form.save(editor=member)
                
                # 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:
                    instance.set_releasedate(form.cleaned_data['releasedate'])
                elif not restricted:
                    instance.set_releasedate(None)

                if not restricted and 'editdate' in form.cleaned_data:
                    instance.set_editdate(form.cleaned_data['editdate'])
                elif not restricted:
                    instance.set_editdate(None)

                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_page.set_releasedate(instance.releasedate())
                    redir_page.set_editdate(instance.editdate())
                    redir_page.save()
                    redir_version = PageVersion(page=redir_page, title=version.title, redirect=instance.label,
                                                editor=member, comment='automatically generated on label change')
                    redir_version.set_redirect_reason('rename')
                    redir_version.save()
                    messages.info(request, 'Page label changed: the old location (%s) will redirect to this page.' % (old_label,))

                instance.save()
                
                #LOG EVENT#
                l = LogEntry(userid=request.user.username,
                      description="Edited page %s in %s." % (instance.label, offering),
                      related_object=instance)
                l.save()
                if page:
                    messages.success(request, "Edited "+kind+" \"%s\"." % (instance.label))
                else:
                    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()
                    offering.set_url(url)
                    offering.save()
                    messages.info(request, "Set course URL to new Index page.")
                
                return HttpResponseRedirect(reverse('pages.views.view_page', kwargs={'course_slug': course_slug, 'page_label': instance.label}))
        else:
            form = Form(instance=page, offering=offering)
            if 'label' in request.GET:
                label = request.GET['label']
                if label == 'Index':
                    form.initial['title'] = offering.name()
                    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
                else:
                    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: views.py
View license
@retry_transaction()
@transaction.atomic
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(activity_id=activity.id).exists()
    if not submission_configured:
        return NotFoundResponse(request)

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

    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
    else:
        late = 0
    
    if activity.group:
        gm = GroupMember.objects.filter(student__person=student, activity=activity, confirmed=True)
        if gm:
            group = gm[0].group
            member = gm[0].student
        else:
            group = None

    else:
        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)
    component_list.sort()
    component_form_list=[]

    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 activity.group:
            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()
            new_sub.group = group
            new_sub.creator = member
        else:
            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 = form.save(commit=False)
                sub.component = component
                submitted_comp.append(sub)
            else:
                # 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."

                not_submitted_comp.append(component)
        # 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
                    to_be_removed.append(i)
                    not_submitted_comp.append(s.component)
                    #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
            to_be_removed.reverse()
            for t in to_be_removed:
                submitted_comp.pop(t)
        # all okay now
        # end validating, begin saving
        if len(submitted_comp) > 0:
            new_sub.save()    
        for sub in submitted_comp:
            sub.submission = new_sub
            sub.save()
            #LOG EVENT#
            if activity.group:
                group_str = " as a member of group %s" % new_sub.group.name
            else:
                group_str = ""
            l = LogEntry(userid=request.user.username,
                  description=u"submitted for %s %s%s" % (activity, sub.component.title, group_str),
                  related_object=sub)
            l.save()

        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: mybitbank
Source File: views.py
View license
@login_required
def send(request, selected_provider_id):
    '''
    handler for the transfers
    '''
    post_errors = []
    selected_provider_id = int(selected_provider_id)
    
    # set the request in the connector object
    connector.request = request
    
    if request.method == 'POST': 
        # we have a POST request
        form = forms.SendCurrencyForm(request.POST)
        
        if form.is_valid():
            # all validation rules pass
            from_account_identifier = form.cleaned_data['from_account']
            to_address = form.cleaned_data['to_address']
            to_account = form.cleaned_data['to_account']
            comment = form.cleaned_data['comment']
            comment_to = form.cleaned_data['comment_to']
            amount = form.cleaned_data['amount']
            provider_id = form.cleaned_data['provider_id']
            passphrase = form.cleaned_data['passphrase']
            
            # main exit flags
            move_exit = False
            sendfrom_exit = False
            
            # get from account details
            wallet = getWalletByProviderId(connector, selected_provider_id)
            list_of_accounts = wallet.listAccounts(gethidden=True, getarchived=True)
            from_account = None
            for account in list_of_accounts:
                if account['identifier'] == from_account_identifier:
                    from_account = account
                    break
            else:
                # account name not found, display error
                post_errors.append({'message': "The source account was not found!"})
                context = commonContext(request=request, selected_provider_id=provider_id, form=form, errors=post_errors)
                return render(request, 'transfer/index.html', context)
            
            # get to account details if there is one
            to_account = wallet.getAccountByAddress(to_address)
            # if to_account is set then it is a local move, do a move()
            if to_account:
                # this address/account is hosted locally, do a move
                move_exit = connector.moveAmount(
                                                 from_account=from_account['name'],
                                                 to_account=to_account['name'],
                                                 provider_id=provider_id,
                                                 amount=amount,
                                                 comment=comment
                                                )
                
                # if there are errors, show them in the UI
                if move_exit is not True:
                    post_errors.append({'message': move_exit['message']})
                    context = commonContext(request=request, selected_provider_id=provider_id, form=form, errors=post_errors)
                    return render(request, 'transfer/index.html', context)
                
            else:
                # otherwise do a sendfrom(), it is a regular transaction
                if passphrase:
                    # a passphrase was given, unlock wallet first
                    unlock_exit = connector.walletPassphrase(passphrase, provider_id)
                    
                    if unlock_exit is not True:
                        # show form with error
                        post_errors.append({'message': unlock_exit['message']})
                        context = commonContext(request=request, selected_provider_id=provider_id, form=form, errors=post_errors, show_passphrase=True)
                        return render(request, 'transfer/index.html', context)
                
                # to_address not local, do a send
                sendfrom_exit = connector.sendFrom(
                                                   from_account=from_account['name'],
                                                   to_address=to_address,
                                                   amount=amount,
                                                   provider_id=provider_id,
                                                   comment=comment,
                                                   comment_to=comment_to
                                                  )
                
                # if there are errors, show them in the UI
                if type(sendfrom_exit) is dict and sendfrom_exit['code'] < 0:
                    
                    # check if passphrase is needed
                    if sendfrom_exit['code'] == -13:
                        # passphrase is needed
                        show_passphrase = True
                    else:
                        show_passphrase = False
                    
                    if not request.is_secure() and show_passphrase:
                        show_warning_ssl = 1
                    elif request.is_secure() and show_passphrase:
                        show_warning_ssl = -1
                    else:
                        show_warning_ssl = 0
                    
                    # show form with error
                    post_errors.append({'message': sendfrom_exit['message']})
                    context = commonContext(request=request, selected_provider_id=provider_id, form=form, errors=post_errors, show_passphrase=show_passphrase, show_warning_ssl=show_warning_ssl)
                    return render(request, 'transfer/index.html', context)
                
            if passphrase:
                # lock wallet again
                connector.walletLock(provider_id)
                
            # process the data in form.cleaned_data
            if move_exit:
                messages.success(request, 'Local move of %s %s completed from account "%s" to "%s"' % (amount, connector.config[provider_id]['currency'].upper(), from_account['name'], to_account['name']), extra_tags="success")
                events.addEvent(request, 'Local move occurred from "%s" to "%s" in the amount of %s %s' % (from_account['name'], to_account['name'], amount, connector.config[provider_id]['currency'].upper()), 'info')
                return HttpResponseRedirect(reverse('transactions:index', kwargs={'selected_provider_id': selected_provider_id, 'page': '1'}))  # Redirect after POST
            elif sendfrom_exit:
                messages.success(request, 'Transfer of %s %s initialized with transaction id %s' % (amount, connector.config[provider_id]['currency'].upper(), sendfrom_exit), extra_tags="success")
                events.addEvent(request, 'Transfer initialized from "%s" to "%s" of %s %s' % (from_account['name'], to_address, amount, connector.config[provider_id]['currency'].upper()), 'info')
                return HttpResponseRedirect(reverse('transactions:details', kwargs={'provider_id': provider_id, 'txid':sendfrom_exit}))  # Redirect after POST
        
        else:
            # form not valid
            #messages.error(request, 'There were some errors processing this form!', extra_tags="error")
            print "Error processing form!"
            
    else:
        # request not a POST
        form = forms.SendCurrencyForm()
        
    context = commonContext(request=request, selected_provider_id=selected_provider_id, form=form)
    
    return render(request, 'transfer/index.html', context)

Example 27

Project: django-todo
Source File: views.py
View license
@user_passes_test(check_user_allowed)
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
    else:
        list = get_object_or_404(List, id=list_id)
        if list.group 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 = datetime.datetime.now()
    created_date = "%s-%s-%s" % (thedate.year, thedate.month, thedate.day)

    # 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(
            list__group__in=(request.user.groups.all()),
            completed=False).order_by('-created_date')[:50]

    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=True).order_by('-completed_date')[:50]

    else:
        task_list = Item.objects.filter(list=list.id, completed=0)
        completed_list = Item.objects.filter(list=list.id, completed=1)

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

        if form.is_valid():
            new_task = form.save()

            # 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)
    else:
        # 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={
                'assigned_to': request.user.id,
                'priority': 999,
            })

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

Example 28

Project: AutoO_with_django
Source File: views.py
View license
def server(request):
  if 'loginToken' in request.session:
    pass
  else:
    return HttpResponseRedirect('/')

  if 'page' in request.GET and request.GET['page'].isdigit():
    page_get = int(float(request.GET['page']))
  else:
    page_get = 1
  if 'query' in request.GET:
    if request.session['query'].has_key('op'):
      request.session['query'] = {'op':'True'}
      if 'pid' in request.POST:
        if request.POST['pid'] == "":
          try:
            request.session['query_data'].pop('pid')
          except:
            quit
        else:
          request.session['query_data']['pid'] = request.POST['pid']
      if 'ip' in request.POST:
        if request.POST['ip'] == "":
          try:
            request.session['query_data'].pop('ip__contains')
          except:
            a = 1
        else:
          request.session['query_data']['ip__contains'] = request.POST['ip']
      if 'srv' in request.POST:
        if request.POST['srv'] == "":
          try:
            request.session['query_data'].pop('srv')
          except:
            a = 1
        else:
          request.session['query_data']['srv'] = request.POST['srv']
      if 'status' in request.POST:
        if request.POST['status'] == "":
          try:
            request.session['query_data'].pop('status')
          except:
            a = 1
        else:
          request.session['query_data']['status'] = request.POST['status']
      exper = request.session['query_data']
    else:
      request.session['query'] = {'op':'true'}          
      if 'pid' in request.POST and request.POST['pid'] != "":
        request.session['query_data']['pid'] = request.POST['pid']
      if 'ip' in request.POST and request.POST['ip'] != "":
        request.session['query_data']['ip__contains'] = request.POST['ip']
      if 'srv' in request.POST and request.POST['srv'] != "":
        request.session['query_data']['srv'] = request.POST['srv']
      if 'status' in request.POST and request.POST['status'] != "":
        request.session['query_data']['status'] = request.POST['status']
      exper = request.session['query_data']
    
    servers = Server.objects.filter(**exper)
  else:
    request.session['query'] = {}
    request.session['query_data'] = {}
    servers = Server.objects.select_related().all()
  pagin = Paginator(servers,20)
  page_max = pagin.num_pages
  if page_get > page_max:
    page = page_max
  else:
    page = page_get
  data_list = pagin.page(page)
  if 'query' in request.GET:
    url_fp = "?query&page=1"
    if page <= 1:
      url_pp = "?query&page=1"
    else:
      url_pp = "?query&page=" + str((page - 1))
    if page >= page_max:
      url_np = "?query&page=" + str(page_max)
    else:
      url_np = "?query&page=" + str((page + 1))
    url_lp = "?query&page=" + str(page_max)
  else:
    url_fp = "?page=1"
    if page <= 1:
      url_pp = "?page=1"
    else:
      url_pp = "?page=" + str((page - 1))
    if page >= page_max:
      url_np = "?page=" + str(page_max)
    else:
      url_np = "?page=" + str((page + 1))
    url_lp = "?page=" + str(page_max)
  projects = Project.objects.all()
  rsp = render(request, 'user_assets.html', locals())
  return HttpResponse(rsp)

Example 29

Project: AutoO_with_django
Source File: views.py
View license
def admin(request, module="", action=""):
  def logRecord(r_action='', r_table='', r_data=''):
    record_name = request.session['user_name']
    record_time = time.strftime('%Y-%m-%d %H:%M',time.localtime())
    data_str = ''
    for temp in sorted(r_data):
      data_str += str(temp)+'='+r_data[temp]+' '
    log_op = Logrecord(user=record_name, time=record_time, action=r_action, table=r_table, data=data_str)
    log_op.save()
  
  if 'loginToken' in request.session and request.session['user_admin']:
    if module == 'project':
      if action != '':
        if action == "add" and request.session['user_sys']:
          proj_alias = request.POST['alias_name']
          proj_name = request.POST['name']
          proj_remark = request.POST['remark']
          obj = Project(alias=proj_alias, name=proj_name, remark=proj_remark)
          obj.save()
          logRecord(action, 'project', request.POST)
          result = {}
          result['code'] = 1
          result['message'] = "添加成功"
        elif action == "del":
          pid = request.POST['id']
          if request.session['user_sys'] or pid == request.session['user_proj']:
            Project.objects.get(id=pid).delete()
            logRecord(action, 'project', request.POST)
            result = {}
            result['code'] = 1
            result['message'] = "删除成功"
          else:
            result = {}
            result['code'] = 1
            result['message'] = "无权限删除"
        elif action.isdigit():
          return HttpResponse(action)
        else:         
          result = {}
          result['code'] = 0
          result['message'] = "操作失败"
        return HttpResponse(json.dumps(result), content_type="application/json")
      else:
        projects = Project.objects.all().order_by('alias')
        rsp = render(request, 'admin_project.html', locals())
        return HttpResponse(rsp)
    elif module == 'servers':
      if action != '':
        if action == "getinfo":
          if 'ipaddr' in request.POST and request.POST['ipaddr'] != "":
            ipaddr = request.POST['ipaddr']
            data_trans = request.POST['data_trans']
            snmpsession = netsnmp.Session(Version = 2, DestHost = ipaddr, Timeout=50000, ErrorStr='Cannot connect')
            oid_name = netsnmp.Varbind('.1.3.6.1.2.1.1.5.0')  #主机名oid
            bind_name = netsnmp.VarList(oid_name)

            oid_cpu = netsnmp.Varbind('.1.3.6.1.2.1.25.3.3.1.2')  #CPU负载oid
            bind_cpu = netsnmp.VarList(oid_cpu)

            oid_mem = netsnmp.Varbind('.1.3.6.1.2.1.25.2.2.0')  #内存总数oid
            bind_mem = netsnmp.VarList(oid_mem)

            oid_ip = netsnmp.Varbind('.1.3.6.1.2.1.4.20.1.1')  #IP地址oid
            bind_ip = netsnmp.VarList(oid_ip)

            snmp_name = snmpsession.get(bind_name)
            snmp_cpu = snmpsession.walk(bind_cpu)
            snmp_mem = snmpsession.get(bind_mem)
            snmp_ip = snmpsession.walk(bind_ip)

            result_name = snmp_name[0]

            i = 0
            for data in snmp_cpu:
              if data != '':
                i += 1

            result_cpu = i

            result_mem = int(snmp_mem[0])/1024
            if data_trans == "1":
              if result_mem <= 512:
                result_mem = 512
              else:
                result_mem = (result_mem/1024 + 1) * 1024

            result_ip = []
            i = 0
            for data in snmp_ip:
              if data != '127.0.0.1':
                oid = '.1.3.6.1.2.1.4.20.1.2.' + str(data)
                oid_ip_index = netsnmp.Varbind(oid)
                bind_ip_index = netsnmp.VarList(oid_ip_index)
                snmp_ip_index = snmpsession.get(bind_ip_index)
                ip_index = snmp_ip_index[0]
                oid_ip_name = netsnmp.Varbind('.1.3.6.1.2.1.2.2.1.2.' + str(ip_index))
                bind_ip_name = netsnmp.VarList(oid_ip_name)
                snmp_ip_name = snmpsession.get(bind_ip_name)
                ip_name = snmp_ip_name[0]
                result_ip.append(data)

            result = {}
            result['code'] = 0
            result['host'] = result_name
            result['cpu'] = result_cpu
            result['mem'] = result_mem
            result['ip'] = "|".join(result_ip)
            result['ip_disp'] = result['ip'].replace("|","\r\n")
            return HttpResponse(json.dumps(result), content_type="application/json")
          else:
            projects = Project.objects.all().order_by('alias')
            rsp = render(request, 'user_index.html', locals())
            return HttpResponse(rsp)
        elif action == "add":
          asset_pid = request.POST['pid']
          asset_ip = request.POST['ip']
          asset_hostname = request.POST['hostname']
          asset_cpu = request.POST['cpu']
          asset_mem = request.POST['mem']
          asset_disk = request.POST['disk']
          if request.POST['type'] == '1':
            asset_type = "物理机"
          elif request.POST['type'] == '2':
            asset_type = "虚拟机"
          else:
            asset_type = "其他" 
          asset_srv = request.POST['srv']
          asset_desc = request.POST['desc']
          pid = Project.objects.get(id=asset_pid)
          if request.session['user_sys'] or asset_pid == request.session['user_proj']:
            obj = Server(pid=pid,
                         ip=asset_ip,
                         hostname=asset_hostname,
                         cpu=asset_cpu,
                         mem=asset_mem,
                         disk=asset_disk,
                         type=asset_type,
                         srv=asset_srv,
                         desc=asset_desc,
                         status='1')
            obj.save()
            logRecord(action, 'asset', request.POST)
            result = {}
            result['code'] = 1
            result['message'] = "添加成功"
          else:
            result = {}
            result['code'] = 0
            result['message'] = "未授权的操作"
        elif action == "del":
          id = request.POST['id']
          del_data = Server.objects.filter(id=id)
          del_id = str(del_data[0].pid.id)
          if request.session['user_sys'] or del_id == request.session['user_proj']:
            try:
              Server.objects.get(id=id).delete()
              logRecord(action, 'asset', request.POST)
              result = {}
              result['code'] = 1
              result['message'] = "删除成功"
            except:
              result = {}
              result['code'] = 0
              result['message'] = "删除异常"
          else:
              result = {}
              result['code'] = 0
              result['message'] = "未授权的操作"
        elif action.isdigit():
          if 'update' in request.GET:
            asset_pid = request.POST['pid']
            asset_ip = request.POST['ip']
            asset_hostname = request.POST['hostname']
            asset_cpu = request.POST['cpu']
            asset_mem = request.POST['mem']
            asset_disk = request.POST['disk']
            if request.POST['type'] == '1':
              asset_type = "物理机"
            elif request.POST['type'] == '2':
              asset_type = "虚拟机"
            else:
              asset_type = "其他" 
            asset_srv = request.POST['srv']
            asset_desc = request.POST['desc']
            asset_status = request.POST['status']
            asset_cacti = request.POST['cacti']
            asset_nagios = request.POST['nagios']
            if request.session['user_sys'] or asset_pid == request.session['user_proj']:
              try:
                Server.objects.filter(id=action).update(ip=asset_ip,
                  hostname=asset_hostname,
                  cpu=asset_cpu,
                  mem=asset_mem,
                  disk=asset_disk,
                  type=asset_type,
                  srv=asset_srv,
                  desc=asset_desc,
                  status = asset_status,
                  cacti = asset_cacti,
                  nagios = asset_nagios
                )
                logRecord('update', 'asset', request.POST)
                result = {}
                result['code'] = 1
                result['message'] = "资产修改成功"
              except:
                result = {}
                result['code'] = 0
                result['message'] = "资产修改未提交"
            else:
                result = {}
                result['code'] = 0
                result['message'] = "未授权的操作"
            return HttpResponse(json.dumps(result), content_type="application/json")
          else:
            try:
              queryset = Server.objects.select_related().get(id=action)
            except:
              return HttpResponse('无效ID')
            rsp = render(request, 'admin_display_server.html', locals())
            return HttpResponse(rsp)
        else:
          result = {}
          result['code'] = 0
          result['message'] = "操作失败"
        return HttpResponse(json.dumps(result), content_type="application/json")
      else:
        if 'page' in request.GET and request.GET['page'].isdigit():
          page_get = int(float(request.GET['page']))
        else:
          page_get = 1
        if 'query' in request.GET:
          if request.session['query'].has_key('op'):
            request.session['query'] = {'op':'True'}
            if 'pid' in request.POST:
              if request.POST['pid'] == "":
                try:
                  request.session['query_data'].pop('pid')
                except:
                  a = 1
              else:
                request.session['query_data']['pid'] = request.POST['pid']
            if 'ip' in request.POST:
              if request.POST['ip'] == "":
                try:
                  request.session['query_data'].pop('ip__contains')
                except:
                  a = 1
              else:
                request.session['query_data']['ip__contains'] = request.POST['ip']
            if 'srv' in request.POST:
              if request.POST['srv'] == "":
                try:
                  request.session['query_data'].pop('srv')
                except:
                  a = 1
              else:
                request.session['query_data']['srv'] = request.POST['srv']
            if 'status' in request.POST:
              if request.POST['status'] == "":
                try:
                  request.session['query_data'].pop('status')
                except:
                  a = 1
              else:
                request.session['query_data']['status'] = request.POST['status']
            exper = request.session['query_data']
          else:
            request.session['query'] = {'op':'true'}          
            if 'pid' in request.POST and request.POST['pid'] != "":
              request.session['query_data']['pid'] = request.POST['pid']
            if 'ip' in request.POST and request.POST['ip'] != "":
              request.session['query_data']['ip__contains'] = request.POST['ip']
            if 'srv' in request.POST and request.POST['srv'] != "":
              request.session['query_data']['srv'] = request.POST['srv']
            if 'status' in request.POST and request.POST['status'] != "":
              request.session['query_data']['status'] = request.POST['status']
            exper = request.session['query_data']
          
          servers = Server.objects.filter(**exper)
        else:
          request.session['query'] = {}
          request.session['query_data'] = {}
          if request.session['user_sys']:
            servers = Server.objects.select_related().all()
          else:
            servers = Server.objects.select_related().filter(pid=request.session['user_proj'])
        pagin = Paginator(servers,20)
        page_max = pagin.num_pages
        if page_get > page_max:
          page = page_max
        else:
          page = page_get
        data_list = pagin.page(page)
        if 'query' in request.GET:
          url_fp = "?query&page=1"
          if page <= 1:
            url_pp = "?query&page=1"
          else:
            url_pp = "?query&page=" + str((page - 1))
          if page >= page_max:
            url_np = "?query&page=" + str(page_max)
          else:
            url_np = "?query&page=" + str((page + 1))
          url_lp = "?query&page=" + str(page_max)
        else:
          url_fp = "?page=1"
          if page <= 1:
            url_pp = "?page=1"
          else:
            url_pp = "?page=" + str((page - 1))
          if page >= page_max:
            url_np = "?page=" + str(page_max)
          else:
            url_np = "?page=" + str((page + 1))
          url_lp = "?page=" + str(page_max)
        if request.session['user_sys']:
          projects = Project.objects.all().order_by('alias')
        else:
          projects = Project.objects.filter(id=request.session['user_proj']).order_by('alias')
        rsp = render(request, 'admin_servers.html', locals())
        return HttpResponse(rsp)
    else:
      rsp = render(request, 'admin_base.html', locals())
      return HttpResponse(rsp)
  else:
    return HttpResponseRedirect('/')

Example 30

Project: django-page-cms
Source File: views.py
View license
    def __call__(self, request, path=None, lang=None, delegation=True,
            **kwargs):

        current_page = False

        if path is None:
            raise ValueError(
                "pages.views.Details class view requires the path argument. "
                "Check your urls.py file.")

        # for the ones that might have forgotten to pass the language
        # the language is now removed from the page path
        if settings.PAGE_USE_LANGUAGE_PREFIX and lang is None:
            maybe_lang = path.split("/")[0]
            if maybe_lang in LANGUAGE_KEYS:
                lang = maybe_lang
                path = path[(len(lang) + 1):]

        lang = self.choose_language(lang, request)
        pages_navigation = self.get_navigation(request, path, lang)

        context = {
            'path': path,
            'pages_navigation': pages_navigation,
            'lang': lang,
        }

        is_staff = self.is_user_staff(request)

        current_page = self.resolve_page(request, context, is_staff)

        # Do redirect to new page (if enabled)
        if settings.PAGE_REDIRECT_OLD_SLUG and current_page:
            url = current_page.get_absolute_url(language=lang)
            slug = current_page.get_complete_slug(language=lang)
            current_url = request.get_full_path()
            if url != path and url + '/' != current_url and slug != path:
                return HttpResponsePermanentRedirect(url)

        # if no pages has been found, we will try to find it via an Alias
        if not current_page:
            redirection = self.resolve_alias(request, path, lang)
            if redirection:
                return redirection
        else:
            context['current_page'] = current_page

        # If unauthorized to see the pages, raise a 404, That can
        # happen with expired pages.
        if not is_staff and not current_page.visible:
            raise Http404

        redirection = self.resolve_redirection(request, context)
        if redirection:
            return redirection

        template_name = self.get_template(request, context)

        self.extra_context(request, context)

        if delegation and current_page.delegate_to:
            answer = self.delegate(request, context, delegation, **kwargs)
            if answer:
                return answer

        if kwargs.get('only_context', False):
            return context
        template_name = kwargs.get('template_name', template_name)
        return render(request, template_name, context)

Example 31

Project: django-annoying
Source File: decorators.py
View license
def render_to(template=None, content_type=None, mimetype=None):
    """
    Decorator for Django views that sends returned dict to render_to_response
    function.

    Template name can be decorator parameter or TEMPLATE item in returned
    dictionary.  RequestContext always added as context instance.
    If view doesn't return dict then decorator simply returns output.

    Parameters:
     - template: template name to use
     - content_type: content type to send in response headers
     - mimetype: content type to send in response headers (deprecated)

    Examples:
    # 1. Template name in decorator parameters

    @render_to('template.html')
    def foo(request):
        bar = Bar.object.all()
        return {'bar': bar}

    # equals to
    def foo(request):
        bar = Bar.object.all()
        return render_to_response('template.html',
                                  {'bar': bar},
                                  context_instance=RequestContext(request))


    # 2. Template name as TEMPLATE item value in return dictionary.
         if TEMPLATE is given then its value will have higher priority
         than render_to argument.

    @render_to()
    def foo(request, category):
        template_name = '%s.html' % category
        return {'bar': bar, 'TEMPLATE': template_name}

    #equals to
    def foo(request, category):
        template_name = '%s.html' % category
        return render_to_response(template_name,
                                  {'bar': bar},
                                  context_instance=RequestContext(request))

    """
    def renderer(function):
        @wraps(function)
        def wrapper(request, *args, **kwargs):
            output = function(request, *args, **kwargs)
            if not isinstance(output, dict):
                return output
            tmpl = output.pop('TEMPLATE', template)
            if tmpl is None:
                template_dir = os.path.join(*function.__module__.split('.')[:-1])
                tmpl = os.path.join(template_dir, function.func_name + ".html")
            # Explicit version check to avoid swallowing other exceptions
            if DJANGO_VERSION >= (1, 9):
                return render(request, tmpl, output,
                              content_type=content_type or mimetype)
            elif DJANGO_VERSION >= (1, 5):
                return render_to_response(tmpl, output,
                        context_instance=RequestContext(request),
                        content_type=content_type or mimetype)
            else:
                return render_to_response(tmpl, output,
                        context_instance=RequestContext(request),
                        mimetype=content_type or mimetype)
        return wrapper
    return renderer

Example 32

Project: djangobb
Source File: views.py
View license
def search(request):
    # TODO: used forms in every search type

    def _render_search_form(form=None):
        return render(request, 'djangobb_forum/search_form.html', {'categories': Category.objects.all(),
                'form': form,
                })

    if not 'action' in request.GET:
        return _render_search_form(form=PostSearchForm())

    if request.GET.get("show_as") == "posts":
        show_as_posts = True
        template_name = 'djangobb_forum/search_posts.html'
    else:
        show_as_posts = False
        template_name = 'djangobb_forum/search_topics.html'

    context = {}

    # Create 'user viewable' pre-filtered topics/posts querysets
    viewable_category = Category.objects.all()
    topics = Topic.objects.all().order_by("-last_post__created")
    posts = Post.objects.all().order_by('-created')
    user = request.user
    if not user.is_superuser:
        user_groups = user.groups.all() or [] # need 'or []' for anonymous user otherwise: 'EmptyManager' object is not iterable
        viewable_category = viewable_category.filter(Q(groups__in=user_groups) | Q(groups__isnull=True))

        topics = Topic.objects.filter(forum__category__in=viewable_category)
        posts = Post.objects.filter(topic__forum__category__in=viewable_category)

    base_url = None
    _generic_context = True

    action = request.GET['action']
    if action == 'show_24h':
        date = timezone.now() - timedelta(days=1)
        if show_as_posts:
            context["posts"] = posts.filter(Q(created__gte=date) | Q(updated__gte=date))
        else:
            context["topics"] = topics.filter(Q(last_post__created__gte=date) | Q(last_post__updated__gte=date))
        _generic_context = False
    elif action == 'show_new':
        if not user.is_authenticated():
            raise Http404("Search 'show_new' not available for anonymous user.")
        try:
            last_read = PostTracking.objects.get(user=user).last_read
        except PostTracking.DoesNotExist:
            last_read = None

        if last_read:
            if show_as_posts:
                context["posts"] = posts.filter(Q(created__gte=last_read) | Q(updated__gte=last_read))
            else:
                context["topics"] = topics.filter(Q(last_post__created__gte=last_read) | Q(last_post__updated__gte=last_read))
            _generic_context = False
        else:
            #searching more than forum_settings.SEARCH_PAGE_SIZE in this way - not good idea :]
            topics_id = [topic.id for topic in topics[:forum_settings.SEARCH_PAGE_SIZE] if forum_extras.has_unreads(topic, user)]
            topics = Topic.objects.filter(id__in=topics_id) # to create QuerySet

    elif action == 'show_unanswered':
        topics = topics.filter(post_count=1)
    elif action == 'show_subscriptions':
        topics = topics.filter(subscribers__id=user.id)
    elif action == 'show_user':
        # Show all posts from user or topics started by user
        if not user.is_authenticated():
            raise Http404("Search 'show_user' not available for anonymous user.")

        user_id = request.GET.get("user_id", user.id)
        try:
            user_id = int(user_id)
        except ValueError:
            raise SuspiciousOperation()

        if user_id != user.id:
            try:
                search_user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                messages.error(request, _("Error: User unknown!"))
                return HttpResponseRedirect(request.path)
            messages.info(request, _("Filter by user '%(username)s'.") % {'username': search_user.username})

        if show_as_posts:
            posts = posts.filter(user__id=user_id)
        else:
            # show as topic
            topics = topics.filter(posts__user__id=user_id).order_by("-last_post__created").distinct()

        base_url = "?action=show_user&user_id=%s&show_as=" % user_id
    elif action == 'search':
        form = PostSearchForm(request.GET)
        if not form.is_valid():
            return _render_search_form(form)

        keywords = form.cleaned_data['keywords']
        author = form.cleaned_data['author']
        forum = form.cleaned_data['forum']
        search_in = form.cleaned_data['search_in']
        sort_by = form.cleaned_data['sort_by']
        sort_dir = form.cleaned_data['sort_dir']

        query = SearchQuerySet().models(Post)

        if author:
            query = query.filter(author__username=author)

        if forum != '0':
            query = query.filter(forum__id=forum)

        if keywords:
            if search_in == 'all':
                query = query.filter(SQ(topic=keywords) | SQ(text=keywords))
            elif search_in == 'message':
                query = query.filter(text=keywords)
            elif search_in == 'topic':
                query = query.filter(topic=keywords)

        order = {'0': 'created',
                 '1': 'author',
                 '2': 'topic',
                 '3': 'forum'}.get(sort_by, 'created')
        if sort_dir == 'DESC':
            order = '-' + order

        post_pks = query.values_list("pk", flat=True)

        if not show_as_posts:
            # TODO: We have here a problem to get a list of topics without double entries.
            # Maybe we must add a search index over topics?

            # Info: If whoosh backend used, setup HAYSTACK_ITERATOR_LOAD_PER_QUERY
            #    to a higher number to speed up
            context["topics"] = topics.filter(posts__in=post_pks).distinct()
        else:
            # FIXME: How to use the pre-filtered query from above?
            posts = posts.filter(pk__in=post_pks).order_by(order)
            context["posts"] = posts

        get_query_dict = request.GET.copy()
        get_query_dict.pop("show_as")
        base_url = "?%s&show_as=" % get_query_dict.urlencode()
        _generic_context = False

    if _generic_context:
        if show_as_posts:
            context["posts"] = posts.filter(topic__in=topics).order_by('-created')
        else:
            context["topics"] = topics

    if base_url is None:
        base_url = "?action=%s&show_as=" % action

    if show_as_posts:
        context['posts_page'] = get_page(context['posts'], request, forum_settings.SEARCH_PAGE_SIZE)
        context["as_topic_url"] = base_url + "topics"
        post_count = context["posts"].count()
        messages.success(request, _("Found %i posts.") % post_count)
    else:
        context['topics_page'] = get_page(context['topics'], request, forum_settings.SEARCH_PAGE_SIZE)
        context["as_post_url"] = base_url + "posts"
        topic_count = context["topics"].count()
        messages.success(request, _("Found %i topics.") % topic_count)

    return render(request, template_name, context)

Example 33

Project: djangobb
Source File: views.py
View license
@transaction.atomic
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 topic.forum.category.has_access(request.user):
        raise PermissionDenied
    Topic.objects.filter(pk=topic.id).update(views=F('views') + 1)

    last_post = topic.last_post

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

    moderator = request.user.is_superuser or request.user in topic.forum.moderators.all()
    if user_is_authenticated and request.user in topic.subscribers.all():
        subscribed = True
    else:
        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 = reply_form.save()
                messages.success(request, _("Your reply saved."))
                return HttpResponseRedirect(post.get_absolute_url())
        else:
            reply_form = AddPostForm(
                initial={
                    'markup': request.user.forum_profile.markup,
                    'subscribe': request.user.forum_profile.auto_subscribe,
                },
                **post_form_kwargs
            )

    # handle poll, if exists
    poll_form = None
    polls = topic.poll_set.all()
    if not polls:
        poll = None
    else:
        poll = polls[0]
        if user_is_authenticated: # Only logged in users can vote
            poll.deactivate_if_expired()
            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 poll.active and not has_voted:
                    poll_form = VotePollForm(poll)
            else:
                if not poll.active:
                    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:
        view_data.update({
            '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)
    else:
        return render(request, 'djangobb_forum/lofi/topic.html', view_data)

Example 34

Project: froide
Source File: views.py
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))
        context.update({
            '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)
        context.update({
            'topic': topic,
        })
    elif tag is not None:
        tag = get_object_or_404(Tag, slug=tag)
        foi_requests = manager.for_list_view().filter(tags=tag)
        context.update({
            'tag': tag
        })
    else:
        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)
        context.update({
            '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)
        context.update({
            'public_body': public_body
        })
        context['filtered'] = True
        context['jurisdiction_list'] = Jurisdiction.objects.get_visible()
    else:
        context['jurisdiction_list'] = Jurisdiction.objects.get_visible()
        context['filtered'] = False

    if feed is not None:
        if feed == 'rss':
            klass = LatestFoiRequestsFeed
        else:
            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)
    try:
        foi_requests = paginator.page(page)
    except PageNotAnInteger:
        foi_requests = paginator.page(1)
    except EmptyPage:
        foi_requests = paginator.page(paginator.num_pages)

    context.update({
        'page_title': _("FoI Requests"),
        'count': count,
        'not_foi': not_foi,
        'object_list': foi_requests,
        'status_list': [(str(x[0]),
            FoiRequest.get_readable_status(x[2]),
            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: views.py
View license
@require_POST
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,
                slug=public_body)
        if not public_body.email:
            raise Http404
        all_laws = FoiLaw.objects.filter(jurisdiction=public_body.jurisdiction)
    else:
        all_laws = FoiLaw.objects.all()
    context = {"public_body": public_body}

    request_form = RequestForm(user=request.user,
                               list_of_laws=all_laws,
                               default_law=FoiLaw.get_default_law(),
                               data=request.POST)
    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)
        else:
            error = True

    if not request_form.is_valid():
        error = True
    else:
        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
    else:
        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 public_body.pk is None:
        public_body._created_by = user
        public_body.save()
        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
        else:
            foi_law = request_form.foi_law

    kwargs = registry.run_hook('pre_request_creation', request,
        user=user,
        public_body=public_body,
        foi_law=foi_law,
        form_data=request_form.cleaned_data,
        post_data=request.POST
    )
    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.'))
        else:
            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)
    else:
        AccountManager(user).send_confirmation_mail(request_id=foi_request.pk,
                password=password)
        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: admin.py
View license
    def entries_view(self, request, form_id, show=False, export=False,
                     export_xls=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()
                try:
                    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])
                writerow(entries_form.columns())
                for row in entries_form.rows(csv=True):
                    writerow(row)
                data = queue.getvalue()
                response.write(data)
                return response
            elif XLWT_INSTALLED and export_xls:
                response = HttpResponse(content_type="application/vnd.ms-excel")
                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)
                        else:
                            sheet.write(r + 2, c, item)
                workbook.save(queue)
                data = queue.getvalue()
                response.write(data)
                return response
            elif request.POST.get("delete") and can_delete_entries:
                selected = request.POST.getlist("selected")
                if selected:
                    try:
                        from django.contrib.messages import info
                    except ImportError:
                        def info(request, message, fail_silently=True):
                            request.user.message_set.create(message=message)
                    entries = self.formentry_model.objects.filter(id__in=selected)
                    count = entries.count()
                    if count > 0:
                        entries.delete()
                        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: filebrowser-safe
Source File: views.py
View license
@xframe_options_sameorigin
def browse(request):
    """
    Browse Files/Directories.
    """

    # QUERY / PATH CHECK
    query = request.GET.copy()
    path = get_path(query.get('dir', ''))
    directory = get_path('')

    if path is None:
        msg = _('The requested Folder does not exist.')
        messages.add_message(request, messages.ERROR, msg)
        if directory is None:
            # The directory returned by get_directory() does not exist, raise an error to prevent eternal redirecting.
            raise ImproperlyConfigured(_("Error finding Upload-Folder. Maybe it does not exist?"))
        redirect_url = reverse("fb_browse") + query_helper(query, "", "dir")
        return HttpResponseRedirect(redirect_url)
    abs_path = os.path.join(get_directory(), path)

    # INITIAL VARIABLES
    results_var = {'results_total': 0, 'results_current': 0, 'delete_total': 0, 'images_total': 0, 'select_total': 0}
    counter = {}
    for k, v in EXTENSIONS.items():
        counter[k] = 0

    dir_list, file_list = default_storage.listdir(abs_path)
    files = []
    for file in dir_list + file_list:

        # EXCLUDE FILES MATCHING ANY OF THE EXCLUDE PATTERNS
        filtered = not file or file.startswith('.')
        for re_prefix in filter_re:
            if re_prefix.search(file):
                filtered = True
        if filtered:
            continue
        results_var['results_total'] += 1

        # CREATE FILEOBJECT
        url_path = "/".join([s.strip("/") for s in
                            [get_directory(), path, file] if s.strip("/")])
        fileobject = FileObject(url_path)

        # FILTER / SEARCH
        append = False
        if fileobject.filetype == request.GET.get('filter_type', fileobject.filetype) and get_filterdate(request.GET.get('filter_date', ''), fileobject.date):
            append = True
        if request.GET.get('q') and not re.compile(request.GET.get('q').lower(), re.M).search(file.lower()):
            append = False

        # APPEND FILE_LIST
        if append:
            try:
                # COUNTER/RESULTS
                if fileobject.filetype == 'Image':
                    results_var['images_total'] += 1
                if fileobject.filetype != 'Folder':
                    results_var['delete_total'] += 1
                elif fileobject.filetype == 'Folder' and fileobject.is_empty:
                    results_var['delete_total'] += 1
                if query.get('type') and query.get('type') in SELECT_FORMATS and fileobject.filetype in SELECT_FORMATS[query.get('type')]:
                    results_var['select_total'] += 1
                elif not query.get('type'):
                    results_var['select_total'] += 1
            except OSError:
                # Ignore items that have problems
                continue
            else:
                files.append(fileobject)
                results_var['results_current'] += 1

        # COUNTER/RESULTS
        if fileobject.filetype:
            counter[fileobject.filetype] += 1

    # SORTING
    query['o'] = request.GET.get('o', DEFAULT_SORTING_BY)
    query['ot'] = request.GET.get('ot', DEFAULT_SORTING_ORDER)
    defaultValue = ''
    if query['o'] in ['date', 'filesize']:
        defaultValue = 0.0
    files = sorted(files, key=lambda f: getattr(f, query['o']) or defaultValue)
    if not request.GET.get('ot') and DEFAULT_SORTING_ORDER == "desc" or request.GET.get('ot') == "desc":
        files.reverse()

    p = Paginator(files, LIST_PER_PAGE)
    try:
        page_nr = request.GET.get('p', '1')
    except:
        page_nr = 1
    try:
        page = p.page(page_nr)
    except (EmptyPage, InvalidPage):
        page = p.page(p.num_pages)

    return render(request, 'filebrowser/index.html', {
        'dir': path,
        'p': p,
        'page': page,
        'results_var': results_var,
        'counter': counter,
        'query': query,
        'title': _(u'Media Library'),
        'settings_var': get_settings_var(),
        'breadcrumbs': get_breadcrumbs(query, path),
        'breadcrumbs_title': ""
    })

Example 38

Project: volontulo
Source File: offers.py
View license
    @staticmethod
    def post(request, slug, id_):  # pylint: disable=unused-argument
        u"""Method resposible for saving changed offer.

        :param request: WSGIRequest instance
        :param slug: string Offer title slugified
        :param id_: int Offer database unique identifier (primary key)
        """
        offer = Offer.objects.get(id=id_)
        if request.POST.get('submit') == 'save_image' and request.FILES:
            form = OfferImageForm(request.POST, request.FILES)
            if form.is_valid():
                offer.save_offer_image(
                    form.save(commit=False),
                    request.user.userprofile,
                    form.cleaned_data['is_main']
                )
                messages.success(request, u"Dodano zdjęcie do galerii.")
            else:
                messages.error(
                    request,
                    u"Problem w trakcie dodawania grafiki: {}".format(
                        '<br />'.join(form.errors)
                    )
                )

            return redirect(
                reverse(
                    'offers_edit',
                    args=[slugify(offer.title), offer.id]
                )
            )
        elif request.POST.get('close_offer') == 'close':
            offer.close_offer()
            return redirect(
                reverse(
                    'offers_view',
                    args=[slugify(offer.title), offer.id]
                )
            )
        elif request.POST.get('status_flag') == 'change_status':
            if request.POST.get('status') == 'published':
                offer.publish()
                if request.user.userprofile.is_administrator:
                    return redirect('offers_reorder', offer.id)
            elif request.POST.get('status') == 'rejected':
                offer.reject()
            return redirect('offers_list')

        form = CreateOfferForm(  # pylint: disable=redefined-variable-type
            request.POST, instance=offer
        )

        if form.is_valid():
            offer = form.save()
            offer.unpublish()
            offer.save()
            save_history(request, offer, action=CHANGE)
            messages.success(request, u"Oferta została zmieniona.")
        else:
            messages.error(
                request,
                u"Formularz zawiera niepoprawnie wypełnione pola: {}".format(
                    '<br />'.join(form.errors)
                )
            )

        if offer.id or request.user.userprofile.is_administrator:
            organizations = [offer.organization]
        else:
            organizations = request.user.userprofile.organizations.all()

        return render(
            request,
            'offers/offer_form.html',
            {
                'offer': offer,
                'form': form,
                'organizations': organizations,
                'offer_image_form': OfferImageForm(),
            }
        )

Example 39

Project: volontulo
Source File: __init__.py
View license
@login_required
def logged_user_profile(request):
    u"""View to display user profile page.

    :param request: WSGIRequest instance
    """
    def _init_edit_profile_form():
        u"""Initialize EditProfileForm - helper method."""
        return EditProfileForm(
            initial={
                'phone_no': request.user.userprofile.phone_no,
                'first_name': request.user.first_name,
                'last_name': request.user.last_name,
                'user': request.user.id,
            }
        )

    def _populate_participated_offers(request):
        u"""Populate offers that current user participate."""
        return Offer.objects.filter(volunteers=request.user)

    def _populate_created_offers(request):
        u"""Populate offers that current user create."""
        return Offer.objects.filter(
            organization__userprofiles__user=request.user
        )

    def _is_saving_user_avatar():
        u"""."""
        return request.POST.get('submit') == 'save_image' and request.FILES

    def _is_saving_organization_image():
        u"""."""
        submit_value = request.POST.get('submit')
        return submit_value == 'save_organization_image' and request.FILES

    def _is_saving_profile():
        u"""."""
        return request.POST.get('submit') == 'save_profile'

    def _save_userprofile():
        u"""Save user profile"""
        form = EditProfileForm(request.POST)
        if form.is_valid():
            user = User.objects.get(id=request.user.id)
            if (
                    form.cleaned_data['current_password'] and
                    form.cleaned_data['new_password'] and
                    form.cleaned_data['confirm_new_password']
            ):
                user.set_password(form.cleaned_data['new_password'])
            user.userprofile.phone_no = form.cleaned_data['phone_no']
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.userprofile.save()
            user.save()
            messages.success(
                request,
                u"Zaktualizowano profil"
            )
        else:
            errors = '<br />'.join(form.errors)
            messages.error(
                request,
                u"Problem w trakcie zapisywania profilu: {}".format(errors)
            )
        return form

    def _handle_user_avatar_upload():
        u"""Handle image upload for user profile page."""
        gallery_form = UserGalleryForm(request.POST, request.FILES)
        if gallery_form.is_valid():
            userprofile.clean_images()
            gallery = gallery_form.save(commit=False)
            gallery.userprofile = userprofile
            # User can only change his avatar
            gallery.is_avatar = True
            gallery.save()
            messages.success(request, u"Dodano grafikę")
        else:
            errors = '<br />'.join(gallery_form.errors)
            messages.error(
                request,
                u"Problem w trakcie dodawania grafiki: {}".format(errors)
            )

    def _handle_organization_image_upload():
        u"""Handle image upload for user profile page."""

        def _is_main(form):
            u"""Return True if is_main image was selected."""
            return True if form.cleaned_data['is_main'] else False

        gallery_form = OrganizationGalleryForm(
            userprofile,
            request.POST,
            request.FILES
        )
        if gallery_form.is_valid():
            gallery = gallery_form.save(commit=False)
            gallery.published_by = userprofile
            if _is_main(gallery_form):
                gallery.set_as_main(gallery.organization)
            gallery.save()
            messages.success(request, u"Dodano zdjęcie do galerii.")
        else:
            errors = '<br />'.join(gallery_form.errors)
            messages.error(
                request,
                u"Problem w trakcie dodawania grafiki: {}".format(errors)
            )

    profile_form = _init_edit_profile_form()
    userprofile = UserProfile.objects.get(user=request.user)
    galleries = OrganizationGallery.get_organizations_galleries(
        userprofile
    )

    if request.method == 'POST':
        if _is_saving_user_avatar():
            _handle_user_avatar_upload()
        elif _is_saving_organization_image():
            _handle_organization_image_upload()
            return redirect('logged_user_profile')
        elif _is_saving_profile():
            profile_form = _save_userprofile()

    ctx = dict(
        profile_form=profile_form,
        user_avatar_form=UserGalleryForm(),
        organization_image_form=OrganizationGalleryForm(userprofile),
        galleries=galleries,
        userprofile=userprofile,
        MEDIA_URL=settings.MEDIA_URL
    )
    ctx['participated_offers'] = _populate_participated_offers(request)
    ctx['created_offers'] = _populate_created_offers(request)

    return render(request, 'users/user_profile.html', ctx)

Example 40

Project: WIPSTER
Source File: views.py
View license
def upload_form(request):

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
#            handle_uploaded_file(request.FILES['file'])
#            newsample = Sample(sample = request.FILES['sample'])
            f = request.FILES['sample']

            
            newsample = Sample(
                sample = f,
                ticket = request.POST['ticket'],
                filename = f.name,
                size = f.size,
#                type = f.content_type,
                type = handler.get_filetype(f),
                md5 = handler.get_md5(f),
                sha1 = handler.get_sha1(f),
                sha256 = handler.get_sha256(f),
                fuzzy = handler.get_fuzzy(f),
            )
            #breakdebug
            newsample.save()

            #Do post-processing stuff here
            s = Sample.objects.filter().order_by('-id')[0]
            #s.exif = handler.get_exif(s.sample).encode('ascii', errors='replace')
            #s.exif = unicode(handler.get_exif(s.sample))
            s.exif = handler.get_exif(s.sample)
            
            s.strings = handler.get_strings(s.sample)
            s.balbuzard = handler.get_balbuzard(s.sample)
            s.trid = handler.get_trid(s.sample)

            #SSDEEP/Fuzzy hash comparison
            s.ssdeep_compare = handler.ssdeep_compare(s.fuzzy, s.md5)

            #VirusTotal Search
            vt_res, vt_short_res = handler.get_vt(s.md5)
            if vt_res:
                s.vt = vt_res
                s.vt_short = vt_short_res

            #If EXE file, run EXE-specific checks
            if "PE32" and "Windows" in s.type:
                s.peframe = handler.get_peframe(s.sample)
                s.pescanner = handler.get_pescanner(s.sample)

            #If PDF file, run PDF-specific checks
            if "PDF" in s.type:
                s.pdfid = handler.get_pdfid(s.sample)
                s.peepdf = handler.get_peepdf(s.sample)
                s.pdf_strings = handler.get_pdfstrings(s.sample)

            #If DOC file, run DOC-specific checks
            if "Document File V2" in s.type:
                s.oleid = handler.get_oleid(s.sample)
                #If valid OLE file, run OLEMETA
                olematch = re.compile(r'\|\s+OLE format\s+\|\s+True\s+\|')
                if olematch.search(s.oleid):
                    s.olemeta = handler.get_olemeta(s.sample)
                #If VBA code detected, run OLEVBA
                vbamatch = re.compile(r'\|\s+VBA Macros\s+\|\s+True\s+\|')
                if vbamatch.search(s.oleid):
                    s.olevba = handler.get_olevba(s.sample)

            #If RTF file, run RTFOBJ
            if "Rich Text Format" in s.type:
                rtfobj, rtflist = handler.get_rtfobj(s.sample)
                s.rtfobj = rtfobj

            #If Objects found, run strings/balbuzard against them
            #REMOVED - TOO RESOURCE-INTENSIVE
#            if rtflist:
#                s.rtfobj_str = handler.get_rtfobj_str(rtflist)
#                s.rtfobj_balbuz = handler.get_rtfobj_balbuz(rtflist)
            
            

            s.save()

            newpage = "/sanalysis/md5/" + s.md5 + "/?upload=True"

            return HttpResponseRedirect(newpage)
        else:
            form = UploadFileForm()
            sample = Sample.objects.filter(created__lte=timezone.now()).order_by('-id')[:25]
            return render(request, 'sanalysis/upload_form.html', {'form': form, 'sample': sample},
                            context_instance = RequestContext(request))

#            return HttpResponseRedirect('/sanalysis/')

#            return render(request, 'sanalysis/sample_page.html', {'sample': sample,
#                                                                  'savename': savename,
#                                                                  'ta_use': ta_use,
#                                                                  'ta_analyses': ta_analyses,
#                                                                  'ta_risks': ta_risks,
#                                                                  'ta_network': ta_network,
#                                                                  'ta_ips': ta_ips,
#                                                                  'ta_domains': ta_domains,
#                                                                  'ta_commands': ta_commands,
#                                                                  'ta_submit': ta_submit,
#                                                                  'crits_use': crits_use,
#                                                                  'crits': crits_dict,
#                                                                  'crits_submit': crits_submit, })


    else:
        form = UploadFileForm()
        sample = Sample.objects.filter(created__lte=timezone.now()).order_by('-id')[:25]
        return render(request, 'sanalysis/upload_form.html', {'form': form, 'sample': sample})

Example 41

Project: WIPSTER
Source File: views.py
View license
def sample_page(request,md5):

##################
#### Set Vars ####
##################

#    sample = get_object_or_404(Sample, md5=md5)
    sample = Sample.objects.filter(md5=md5)
    savename = handler.get_savename(sample[sample.count()-1])
    savename = 'samples/'+md5+'/'+savename
    ta_submit = ""
    plaintext = {'vt_short': [],
                 'vt_nums': ""}

    extra_params = "&md5="+md5

    # Process ticket #
    ticket = sample[sample.count()-1].ticket
    zeros = '0' * (12 - len(ticket))
    plaintext['ticket'] = "TICKET" + zeros + ticket
    
    # Process VT #
    if sample[sample.count()-1].vt_short:
        vt_plain_res = sample[sample.count()-1].vt_short
        if "Results:" in vt_plain_res:
            vt_res_split = vt_plain_res.split("\r\n")
            vt_nums_split = vt_res_split[0].split("\t")
            if vt_nums_split > 1:
                plaintext['vt_nums'] = vt_nums_split[1]
            vt_split1 = vt_plain_res.split("\r\n\r\n")
            if len(vt_split1) > 1:
                vt_short_line = vt_split1[1].split("\r\n")
                for line in vt_short_line:
                    if line:
                        vendor_detect_split = line.split(":\t")
                        space_length = " " * (10 - len(vendor_detect_split[0]))
                        vendor_fix = vendor_detect_split[0] + space_length + ":    "
                        plaintext['vt_short'].append({'vendor': vendor_fix,
                                                      'detect': vendor_detect_split[1]})
    #debugerror

################################################
#### Process ThreatAnalyzer POST Submission ####
################################################

    if request.method=="POST" and ta_use:
        if 'ta_submit' in request.POST:
            if request.POST['ta_submit']:

                ta_submit = threatanalyzer.submit_to_ta(md5, savename)

                current_page = "/sanalysis/md5/"+md5+"/"
                return HttpResponseRedirect(current_page)


#### Process ThreatAnalyzer Data ####

    if ta_use:
        ta_analyses, ta_risks, ta_network, ta_ips, ta_domains, ta_commands, ta_dropped = threatanalyzer.get_ta_analyses(md5, extra_params=extra_params)
    else:
        ta_analyses=ta_risks=ta_network = ""
        ta_ips=ta_domains=ta_commands = []

    #Automatically submit to ThreatAnalyzer if ta_autosubmit == True and there is no existing analyses
    if ta_use and ta_autosubmit and "HTTP Error 404" in ta_analyses:
        ta_submit = threatanalyzer.submit_to_ta(md5, savename)    


############################
#### Process CRITs Data ####
############################

    crits_vt = {}
    crits_ta = {}
    crits_dict = {}
    crits_submit = ""
    crits_rel_trace = ""

    if crits_use:
        if sample[sample.count()-1].vt_short:
            vt_short_res = sample[sample.count()-1].vt_short
            crits_vt = crits.crits_vt(vt_short_res)
            if not (ta_ips or ta_domains or ta_commands):
                crits_dict = crits_vt

        if ta_use and (ta_ips or ta_domains or ta_commands):
            crits_ta = crits.crits_parse(ta_ips, ta_domains, ta_commands, ta_dropped)
            if not sample[sample.count()-1].vt_short:    
                crits_dict = crits_ta

        if crits_vt and crits_ta:
            crits_dict.clear()
            crits_dict = crits_vt.copy()
            crits_dict.update(crits_ta)

        crits_dict['page'] = crits_base+"/samples/details/"+sample[sample.count()-1].md5+"/"


    else:
        crits_dict = { 'crits_ips' : [],
                       'crits_domains': [],
                       'crits_uas' : [],
                       'crits_vts' : [],
                       'crits_commands' : [],
                       'page': ""}

############################
#### Process CRITs Form ####
############################

    if request.method=="POST" and crits_use:
        #If submitting new data to CRITs
        if 'crits_submit' in request.POST:
            if request.POST['crits_submit']:
                crits_submit = crits.submit_to_crits(request.POST, sample[sample.count()-1], crits_ta, savename=savename)
        #If trying to get relationships from CRITs DB
        if 'crits_rel_trace' in request.POST:
            if request.POST['crits_rel_trace']:
                
                #### Set the variables for the trace
                
                #Get all tickets related to this sample from the WIPSTER DB
                db_tickets = []
                for i in sample:
                    if i.ticket and i.ticket not in db_tickets:
                        db_tickets.append(i.ticket)
                
                crits_rel_trace_vars = {
                            'md5' : sample[sample.count()-1].md5,
                            'db_tickets' : db_tickets,
                            'depth' : crits_depth,
                            'crits_page' : crits_page,
                            'crits_base' : crits_base,
                            'crits_login' : crits_login,
                            'api_key': crits_api_key,
                            'username': crits_username,
                            'type': "Sample",
                            'cid': ''
                       }
                       
                #Get the relationships for the page display
                crits_rel_trace = crits_relationships.trace_crits_relationships(crits_rel_trace_vars)
                if not crits_rel_trace:
                    crits_rel_trace = "No potentially related tickets were found that are not currently associated with this sample."

    #If crits_autosubmit == True, all samples and tickets will be added to CRITs and related to eachother
    first_upload = request.GET.get('upload', '')
    if crits_use and crits_autosubmit and request.method!="POST" and first_upload:
        request.POST = {}
        crits_submit = crits.submit_to_crits(request.POST, sample[sample.count()-1], crits_ta, savename=savename)

#            current_page = "/sanalysis/md5/"+md5+"/"
#            return HttpResponseRedirect(current_page)

##########################
#### RENDER MAIN PAGE ####
##########################


    return render(request, 'sanalysis/sample_page.html', {'sample': sample,
                                                          'savename': savename,
                                                          'plaintext': plaintext,
                                                          'ta_use': ta_use,
                                                          'ta_analyses': ta_analyses,
                                                          'ta_risks': ta_risks,
                                                          'ta_network': ta_network,
                                                          'ta_ips': ta_ips,
                                                          'ta_domains': ta_domains,
                                                          'ta_commands': ta_commands,
                                                          'ta_dropped': ta_dropped,
                                                          'ta_submit': ta_submit,
                                                          'crits_use': crits_use,
                                                          'crits': crits_dict,
                                                          'crits_submit': crits_submit, 
                                                          'crits_rel_trace': crits_rel_trace,})

Example 42

Project: RatticWeb
Source File: views.py
View license
@login_required
def list(request, cfilter='special', value='all', sortdir='ascending', sort='title', page=1):
    # Setup basic stuff
    viewdict = {
        'credtitle': _('All passwords'),
        'alerts': [],
        'filter': unicode(cfilter).lower(),
        'value': unicode(value).lower(),
        'sort': unicode(sort).lower(),
        'sortdir': unicode(sortdir).lower(),
        'page': unicode(page).lower(),
        'groups': request.user.groups,

        # Default buttons
        'buttons': {
            'add': True,
            'delete': True,
            'changeq': True,
            'tagger': True,
            'export': False,
        }
    }

    # Get groups if required
    get_groups = request.GET.getlist('group')

    if len(get_groups) > 0:
        groups = Group.objects.filter(id__in=get_groups)
    else:
        groups = Group.objects.all()

    # Perform the search
    (search_object, cred_list) = cred_search(request.user, cfilter, value, sortdir, sort, groups)

    # Apply the filters
    if cfilter == 'tag':
        viewdict['credtitle'] = _('Passwords tagged with %(tagname)s') % {'tagname': search_object.name, }
        viewdict['buttons']['export'] = True

    elif cfilter == 'group':
        viewdict['credtitle'] = _('Passwords in group %(groupname)s') % {'groupname': search_object.name, }
        viewdict['buttons']['export'] = True

    elif cfilter == 'search':
        viewdict['credtitle'] = _('Passwords for search "%(searchstring)s"') % {'searchstring': search_object, }
        viewdict['buttons']['export'] = True

    elif cfilter == 'history':
        viewdict['credtitle'] = _('Versions of: "%(credtitle)s"') % {'credtitle': search_object.title, }
        viewdict['buttons']['add'] = False
        viewdict['buttons']['delete'] = False
        viewdict['buttons']['changeq'] = False
        viewdict['buttons']['tagger'] = False

    elif cfilter == 'changeadvice':
        alert = {}
        alert['message'] = _("That user is now disabled. Here is a list of passwords that they have viewed that have not since been changed. You probably want to add them all to the change queue.")
        alert['type'] = 'info'

        viewdict['credtitle'] = _('Changes required for "%(username)s"') % {'username': search_object.username}
        viewdict['buttons']['add'] = False
        viewdict['buttons']['delete'] = True
        viewdict['buttons']['changeq'] = True
        viewdict['buttons']['tagger'] = False
        viewdict['alerts'].append(alert)

    elif cfilter == 'special' and value == 'all':
        viewdict['buttons']['export'] = True

    elif cfilter == 'special' and value == 'trash':
        viewdict['credtitle'] = _('Passwords in the trash')
        viewdict['buttons']['add'] = False
        viewdict['buttons']['undelete'] = True
        viewdict['buttons']['changeq'] = False
        viewdict['buttons']['tagger'] = False
        viewdict['buttons']['export'] = True

    elif cfilter == 'special' and value == 'changeq':
        viewdict['credtitle'] = _('Passwords on the Change Queue')
        viewdict['buttons']['add'] = False
        viewdict['buttons']['delete'] = False
        viewdict['buttons']['changeq'] = False
        viewdict['buttons']['tagger'] = False

    else:
        raise Http404

    # Apply the sorting rules
    if sortdir == 'ascending':
        viewdict['revsortdir'] = 'descending'
    elif sortdir == 'descending':
        viewdict['revsortdir'] = 'ascending'
    else:
        raise Http404

    # Get the page
    paginator = Paginator(cred_list, request.user.profile.items_per_page)
    try:
        cred = paginator.page(page)
    except PageNotAnInteger:
        cred = paginator.page(1)
    except EmptyPage:
        cred = paginator.page(paginator.num_pages)

    # Get variables to give the template
    viewdict['credlist'] = cred

    # Create the form for exporting
    viewdict['exportform'] = ExportForm()

    return render(request, 'cred_list.html', viewdict)

Example 43

Project: RatticWeb
Source File: views.py
View license
@rattic_staff_required
def import_process(request, import_id):
    # If there was no session data, return 404
    if 'imported_data' not in request.session.keys():
        raise Http404

    # Get the entry we are concerned with
    try:
        entry = request.session['imported_data']['entries'][int(import_id)]
    except IndexError:
        raise Http404

    # Get the group
    groupid = request.session['imported_data']['group']
    try:
        group = Group.objects.get(pk=groupid)
    except Group.DoesNotExist:
        del request.session['imported_data']
        raise Http404

    if request.method == 'POST':
        # Try and import what we have now

        # Did the user upload a new attachment
        if entry['filename'] and 'attachment' not in request.FILES.keys():
            sfile = SimpleUploadedFile(entry['filename'], bytes(entry['filecontent']))
            request.FILES['attachment'] = sfile

        # Build the form
        form = CredForm(request.user, request.POST, request.FILES)

        # Do we have enough data to save?
        if form.is_valid():

            # Save the credential
            form.save()

            # Write the audit log
            CredAudit(
                audittype=CredAudit.CREDADD,
                cred=form.instance,
                user=request.user,
            ).save()

            # Remove the entry we're importing
            del request.session['imported_data']['entries'][int(import_id)]
            request.session.save()

            # Go back to the overview
            return HttpResponseRedirect(reverse('staff.views.import_overview'))

    else:
        # Init the cred, and create the form
        processed = dict(entry)

        # Create all the tags
        tlist = []
        for t in processed['tags']:
            (tag, create) = Tag.objects.get_or_create(name=t)
            tlist.append(tag)
        processed['tags'] = tlist

        # Setup the group
        processed['group'] = group

        # If the icon is empty set it
        if 'iconname' not in processed.keys():
            processed['iconname'] = 'Key.png'

        # Remove the attachment
        if processed['filename']:
            del processed['filename']
            del processed['filecontent']

        # Create the form
        form = CredForm(request.user, processed, {})

    return render(request, 'staff_import_process.html', {
        'form': form,
        'icons': get_icon_list(),
    })

Example 44

Project: ion
Source File: activities.py
View license
@eighth_admin_required
def edit_activity_view(request, activity_id):
    try:
        activity = EighthActivity.objects.get(id=activity_id)  # include deleted
    except EighthActivity.DoesNotExist:
        raise http.Http404

    if request.method == "POST":
        form = ActivityForm(request.POST, instance=activity)
        if form.is_valid():
            try:

                # Check if sponsor change
                old_sponsors = activity.sponsors.all()
                old_sponsor_ids = old_sponsors.values_list("id", flat=True)
                new_sponsor_ids = [s.id for s in form.cleaned_data["sponsors"]]

                if set(old_sponsor_ids) != set(new_sponsor_ids) and len(old_sponsor_ids) > 0:
                    start_date = get_start_date(request)
                    sched_acts_default = EighthScheduledActivity.objects.filter(activity=activity, sponsors=None, block__date__lt=start_date)

                    if sched_acts_default.count() > 0:
                        # This will change scheduled activities that used overrides in the past.
                        # Thus, by looping through the scheduled activities that didn't have any
                        # custom sponsors specified, we *could* prevent anything from visibly
                        # changing by making an override with the value of the previous default.

                        # Yes: Save History => Override old values
                        # No: Change Globally => Don't override old values, they will change to new default

                        if "change_sponsor_history" in request.POST:
                            change = request.POST.get("change_sponsor_history")

                            if change == "yes":
                                # Override old entries
                                for sa in sched_acts_default:
                                    for sponsor in old_sponsors:
                                        sa.sponsors.add(sponsor)
                                    sa.save()
                                messages.success(request,
                                                 "Overrode {} scheduled activities to old sponsor default".format(sched_acts_default.count()))
                            elif change == "no":
                                # Don't override
                                messages.success(request, "Changing default sponsors globally")
                                # Continues to form.save()
                        else:
                            # show message, asking whether to change history
                            context = {
                                "admin_page_title": "Keep Sponsor History?",
                                "activity": activity,
                                "sched_acts_count": sched_acts_default.count(),
                                "start_date": start_date,
                                "old_sponsors": EighthSponsor.objects.filter(id__in=old_sponsor_ids),
                                "new_sponsors": EighthSponsor.objects.filter(id__in=new_sponsor_ids),
                                "form": form
                            }
                            return render(request, "eighth/admin/keep_sponsor_history.html", context)
                    else:
                        messages.success(request, "You modified the default sponsors, but those changes will not affect any scheduled activities.")

                # Check if room change
                old_rooms = activity.rooms.all()
                old_room_ids = old_rooms.values_list("id", flat=True)
                new_room_ids = [r.id for r in form.cleaned_data["rooms"]]

                if set(old_room_ids) != set(new_room_ids) and len(old_room_ids) > 0:
                    start_date = get_start_date(request)
                    sched_acts_default = EighthScheduledActivity.objects.filter(activity=activity, rooms=None, block__date__lt=start_date)

                    if sched_acts_default.count() > 0:
                        # This will change scheduled activities that used overrides in the past.
                        # Thus, by looping through the scheduled activities that didn't have any
                        # custom rooms specified, we *could* prevent anything from visibly
                        # changing by making an override with the value of the previous default.

                        # Yes: Save History => Override old values
                        # No: Change Globally => Don't override old values, they will change to new default

                        if "change_room_history" in request.POST:
                            change = request.POST.get("change_room_history")

                            if change == "yes":
                                # Override old entries
                                for sa in sched_acts_default:
                                    for room in old_rooms:
                                        sa.rooms.add(room)
                                    sa.save()
                                messages.success(request, "Overrode {} scheduled activities to old room default".format(sched_acts_default.count()))
                            elif change == "no":
                                # Don't override
                                messages.success(request, "Changing default rooms globally")
                                # Continues to form.save()
                        else:
                            # show message, asking whether to change history
                            context = {
                                "admin_page_title": "Keep Room History?",
                                "activity": activity,
                                "sched_acts_count": sched_acts_default.count(),
                                "start_date": start_date,
                                "old_rooms": EighthRoom.objects.filter(id__in=old_room_ids),
                                "new_rooms": EighthRoom.objects.filter(id__in=new_room_ids),
                                "form": form
                            }
                            return render(request, "eighth/admin/keep_room_history.html", context)
                    else:
                        messages.success(request, "You modified the default rooms, but those changes will not affect any scheduled activities.")

                form.save()
            except forms.ValidationError as error:
                error = str(error)
                messages.error(request, error)
            else:
                messages.success(request, "Successfully edited activity.")
                if "add_group" in request.POST:
                    grp_name = "Activity: {}".format(activity.name)
                    grp, status = Group.objects.get_or_create(name=grp_name)
                    logger.debug(grp)
                    activity.restricted = True
                    activity.groups_allowed.add(grp)
                    activity.save()
                    invalidate_obj(activity)
                    messages.success(request, "{} to '{}' group".format("Created and added" if status else "Added", grp_name))
                    return redirect("eighth_admin_edit_group", grp.id)

                return redirect("eighth_admin_edit_activity", activity_id)
        else:
            messages.error(request, "Error adding activity.")
    else:
        form = ActivityForm(instance=activity)

    activities = EighthActivity.undeleted_objects.order_by("name")

    activity_groups = []
    for g in activity.groups_allowed.all():
        group = {}
        group["id"] = g.id
        group["name"] = "{}".format(g)
        group["members_alpha"] = sorted(g.user_set.all(), key=lambda x: (x.last_name, x.first_name))
        group["members_alpha_count"] = len(group["members_alpha"])
        activity_groups.append(group)

    activity_members = sorted(activity.users_allowed.all(), key=lambda x: (x.last_name, x.first_name))
    context = {
        "form": form,
        "admin_page_title": "Edit Activity",
        "delete_url": reverse("eighth_admin_delete_activity", args=[activity_id]),
        "activity": activity,
        "activity_groups": activity_groups,
        "activities": activities,
        "activity_members": activity_members
    }

    return render(request, "eighth/admin/edit_activity.html", context)

Example 45

Project: ion
Source File: attendance.py
View license
@eighth_admin_required
def delinquent_students_view(request):
    lower_absence_limit = request.GET.get("lower", "")
    upper_absence_limit = request.GET.get("upper", "")

    include_freshmen = (request.GET.get("freshmen", "off") == "on")
    include_sophomores = (request.GET.get("sophomores", "off") == "on")
    include_juniors = (request.GET.get("juniors", "off") == "on")
    include_seniors = (request.GET.get("seniors", "off") == "on")

    if not request.META["QUERY_STRING"]:
        include_freshmen = True
        include_sophomores = True
        include_juniors = True
        include_seniors = True

    start_date = request.GET.get("start", "")
    end_date = request.GET.get("end", "")

    if not lower_absence_limit.isdigit():
        lower_absence_limit = ""
        lower_absence_limit_filter = 1
    else:
        lower_absence_limit_filter = lower_absence_limit

    if not upper_absence_limit.isdigit():
        upper_absence_limit = ""
        upper_absence_limit_filter = 1000
    else:
        upper_absence_limit_filter = upper_absence_limit

    try:
        start_date = datetime.strptime(start_date, "%Y-%m-%d")
        start_date_filter = start_date
    except ValueError:
        start_date = ""
        start_date_filter = date(MINYEAR, 1, 1)

    try:
        end_date = datetime.strptime(end_date, "%Y-%m-%d")
        end_date_filter = end_date
    except ValueError:
        end_date = ""
        end_date_filter = date(MAXYEAR, 12, 31)

    context = {
        "lower_absence_limit": lower_absence_limit,
        "upper_absence_limit": upper_absence_limit,
        "include_freshmen": include_freshmen,
        "include_sophomores": include_sophomores,
        "include_juniors": include_juniors,
        "include_seniors": include_seniors,
        "start_date": start_date,
        "end_date": end_date
    }

    query_params = ["lower", "upper", "freshmen", "sophomores", "juniors", "seniors", "start", "end"]

    if set(request.GET.keys()).intersection(set(query_params)):
        # attendance MUST have been taken on the activity for the absence to be valid
        non_delinquents = []
        delinquents = []
        if int(upper_absence_limit_filter) == 0 or int(lower_absence_limit_filter) == 0:
            users_with_absence = (EighthSignup.objects.filter(
                was_absent=True, scheduled_activity__attendance_taken=True, scheduled_activity__block__date__gte=start_date_filter,
                scheduled_activity__block__date__lte=end_date_filter).values("user").annotate(absences=Count("user")).filter(absences__gte=1)
                .values("user", "absences").order_by("user"))

            uids_with_absence = [row["user"] for row in users_with_absence]
            all_students = User.objects.get_students().values_list("id")
            uids_all_students = [row[0] for row in all_students]
            uids_without_absence = set(uids_all_students) - set(uids_with_absence)
            users_without_absence = User.objects.filter(id__in=uids_without_absence).order_by("id")
            non_delinquents = []
            for usr in users_without_absence:
                non_delinquents.append({"absences": 0, "user": usr})

            logger.debug(non_delinquents)

        if int(upper_absence_limit_filter) > 0:
            delinquents = (EighthSignup.objects.filter(
                was_absent=True, scheduled_activity__attendance_taken=True, scheduled_activity__block__date__gte=start_date_filter,
                scheduled_activity__block__date__lte=end_date_filter).values("user").annotate(absences=Count("user"))
                .filter(absences__gte=lower_absence_limit_filter,
                        absences__lte=upper_absence_limit_filter).values("user", "absences").order_by("user"))

            user_ids = [d["user"] for d in delinquents]
            delinquent_users = User.objects.filter(id__in=user_ids).order_by("id")
            for index, user in enumerate(delinquent_users):
                delinquents[index]["user"] = user
            logger.debug(delinquents)

            delinquents = list(delinquents)

        delinquents += non_delinquents

        def filter_by_grade(delinquent):
            grade = delinquent["user"].grade.number
            include = False
            if include_freshmen:
                include |= (grade == 9)
            if include_sophomores:
                include |= (grade == 10)
            if include_juniors:
                include |= (grade == 11)
            if include_seniors:
                include |= (grade == 12)
            return include

        delinquents = list(filter(filter_by_grade, delinquents))
        # most absences at top
        delinquents = sorted(delinquents, key=lambda x: (-1 * x["absences"], x["user"].last_name))

        logger.debug(delinquents)
    else:
        delinquents = None

    context["delinquents"] = delinquents

    if request.resolver_match.url_name == "eighth_admin_view_delinquent_students":
        context["admin_page_title"] = "Delinquent Students"
        return render(request, "eighth/admin/delinquent_students.html", context)
    else:
        response = http.HttpResponse(content_type="text/csv")
        response["Content-Disposition"] = "attachment; filename=\"delinquent_students.csv\""

        writer = csv.writer(response)
        writer.writerow(["Start Date", "End Date", "Absences", "Last Name", "First Name", "Student ID", "Grade", "Counselor", "TJ Email",
                         "Other Email"])

        for delinquent in delinquents:
            row = []
            row.append(str(start_date).split(" ", 1)[0])
            row.append(str(end_date).split(" ", 1)[0])
            row.append(delinquent["absences"])
            row.append(delinquent["user"].last_name)
            row.append(delinquent["user"].first_name)
            row.append(delinquent["user"].student_id)
            row.append(delinquent["user"].grade.number)
            counselor = delinquent["user"].counselor
            row.append(counselor.last_name if counselor else "")
            row.append("{}".format(delinquent["user"].tj_email))
            row.append(delinquent["user"].emails[0] if delinquent["user"].emails and len(delinquent["user"].emails) > 0 else "")
            writer.writerow(row)

        return response

Example 46

Project: ion
Source File: scheduling.py
View license
@eighth_admin_required
def schedule_activity_view(request):

    if request.method == "POST":
        formset = ScheduledActivityFormset(request.POST)

        if formset.is_valid():
            for form in formset:
                block = form.cleaned_data["block"]
                activity = form.cleaned_data["activity"]

                # Save changes to cancelled activities and scheduled activities
                cancelled = (EighthScheduledActivity.objects.filter(block=block, activity=activity, cancelled=True).exists())

                instance = None
                if form["scheduled"].value() or cancelled:
                    instance, created = (EighthScheduledActivity.objects.get_or_create(block=block, activity=activity))
                    invalidate_obj(instance)
                    invalidate_obj(block)
                    invalidate_obj(activity)
                else:
                    schact = EighthScheduledActivity.objects.filter(block=block, activity=activity)
                    logger.debug(block)
                    logger.debug(activity)
                    logger.debug(schact)

                    # Instead of deleting and messing up attendance,
                    # cancel the scheduled activity if it is unscheduled.
                    # If the scheduled activity needs to be completely deleted,
                    # the "Unschedule" box can be checked after it has been cancelled.

                    # If a both blocks activity, unschedule the other
                    # scheduled activities of it on the same day.
                    if schact:
                        if activity.both_blocks:
                            other_act = schact[0].get_both_blocks_sibling()
                            logger.debug("other_act: {}".format(other_act))
                            if other_act:
                                other_act.cancelled = True
                                other_act.save()
                                invalidate_obj(other_act)
                        else:
                            schact.update(cancelled=True)
                            for s in schact:
                                invalidate_obj(s)
                        instance = schact[0]

                        cancelled = True

                if instance:
                    fields = ["rooms", "capacity", "sponsors", "title", "special", "administrative", "restricted", "sticky", "both_blocks", "comments", "admin_comments"]
                    if "rooms" in form.cleaned_data:
                        for o in form.cleaned_data["rooms"]:
                            invalidate_obj(o)

                    if "sponsors" in form.cleaned_data:
                        for o in form.cleaned_data["sponsors"]:
                            invalidate_obj(o)

                    for field_name in fields:
                        obj = form.cleaned_data[field_name]
                        logger.debug("{} {}".format(field_name, obj))
                        # Properly handle ManyToMany relations in django 1.10+
                        if isinstance(getattr(instance, field_name), Manager):
                            getattr(instance, field_name).set(obj)
                        else:
                            setattr(instance, field_name, obj)

                        if field_name in ["rooms", "sponsors"]:
                            for o in obj:
                                invalidate_obj(o)

                if form["scheduled"].value() or cancelled:
                    # Uncancel if this activity/block pairing was already
                    # created and cancelled
                    instance.cancelled = not form["scheduled"].value()

                    # If an activity has already been cancelled and the
                    # unschedule checkbox has been checked, delete the
                    # EighthScheduledActivity instance. If there are students
                    # in the activity then error out.
                    if form["unschedule"].value() and instance.cancelled:
                        name = "{}".format(instance)
                        count = instance.eighthsignup_set.count()
                        logger.debug("Unschedule {} - signups {}".format(name, count))
                        bb_ok = True
                        sibling = False
                        if activity.both_blocks:
                            sibling = instance.get_both_blocks_sibling()
                            if sibling:
                                if not sibling.eighthsignup_set.count() == 0:
                                    bb_ok = False

                        if count == 0 and bb_ok:
                            instance.delete()
                            if sibling:
                                sibling.delete()
                            messages.success(request, "Unscheduled {}".format(name))

                            continue  # don't run instance.save()
                        elif count == 1:
                            messages.error(request, "Did not unschedule {} because there is {} student signed up.".format(name, count))
                        else:
                            messages.error(request, "Did not unschedule {} because there are {} students signed up.".format(name, count))
                    instance.save()
                    logger.debug(instance)

            messages.success(request, "Successfully updated schedule.")

            # Force reload everything from the database to reset
            # forms that weren't saved
            return redirect(request.get_full_path())
        else:
            messages.error(request, "Error updating schedule.")

    activities = EighthActivity.undeleted_objects.order_by("name")
    activity_id = request.GET.get("activity", None)
    activity = None

    if activity_id is not None and len(activity_id) > 0:
        try:
            activity = EighthActivity.undeleted_objects.get(id=activity_id)
        except (EighthActivity.DoesNotExist, ValueError):
            pass

    all_sponsors = {s["id"]: s for s in EighthSponsor.objects.values()}
    all_rooms = {r["id"]: r for r in EighthRoom.objects.values()}

    for sid, sponsor in all_sponsors.items():
        if sponsor["show_full_name"]:
            all_sponsors[sid]["full_name"] = sponsor["last_name"] + ", " + sponsor["first_name"]
        else:
            all_sponsors[sid]["full_name"] = sponsor["last_name"]

    for rid, room in all_rooms.items():
        all_rooms[rid]["description"] = room["name"] + " (" + str(room["capacity"]) + ")"

    all_signups = {}
    all_default_capacities = {}

    context = {
        "activities": activities,
        "activity": activity,
        "sponsors": all_sponsors,
        "all_signups": all_signups,
        "rooms": all_rooms,
        "sponsors_json": safe_json(all_sponsors),
        "rooms_json": safe_json(all_rooms)
    }

    if activity is not None:
        start_date = get_start_date(request)
        # end_date = start_date + timedelta(days=60)

        blocks = EighthBlock.objects.filter(date__gte=start_date)
        # , date__lte=end_date)
        initial_formset_data = []

        sched_act_queryset = (EighthScheduledActivity.objects.filter(activity=activity).select_related("block").prefetch_related("rooms", "sponsors",
                                                                                                                                 "members"))
        all_sched_acts = {sa.block.id: sa for sa in sched_act_queryset}

        for block in blocks:
            initial_form_data = {"block": block, "activity": activity}
            try:
                sched_act = all_sched_acts[block.id]

                all_signups[block.id] = sched_act.members.count()
                all_default_capacities[block.id] = sched_act.get_true_capacity()
                logger.debug(sched_act)
                initial_form_data.update({
                    "rooms": sched_act.rooms.all(),
                    "capacity": sched_act.capacity,
                    "sponsors": sched_act.sponsors.all(),
                    "title": sched_act.title,
                    "special": sched_act.special,
                    "administrative": sched_act.administrative,
                    "restricted": sched_act.restricted,
                    "sticky": sched_act.sticky,
                    "both_blocks": sched_act.both_blocks,
                    "comments": sched_act.comments,
                    "admin_comments": sched_act.admin_comments,
                    "scheduled": not sched_act.cancelled,
                    "cancelled": sched_act.cancelled
                })
            except KeyError:
                all_signups[block.id] = 0
                all_default_capacities[block.id] = activity.capacity()
                pass
            initial_formset_data.append(initial_form_data)

        if request.method != "POST":
            # There must be an error in the form if this is reached
            formset = ScheduledActivityFormset(initial=initial_formset_data)
        context["formset"] = formset
        context["rows"] = list(zip(blocks, formset))

        context["default_rooms"] = activity.rooms.all()
        context["default_sponsors"] = activity.sponsors.all()
        context["default_capacities"] = all_default_capacities

    context["admin_page_title"] = "Schedule an Activity"
    return render(request, "eighth/admin/schedule_activity.html", context)

Example 47

Project: ion
Source File: attendance.py
View license
@attendance_taker_required
def take_attendance_view(request, scheduled_activity_id):
    try:
        scheduled_activity = (EighthScheduledActivity.objects.select_related("activity", "block").get(activity__deleted=False,
                                                                                                      id=scheduled_activity_id))
    except EighthScheduledActivity.DoesNotExist:
        raise http.Http404

    if request.user.is_eighth_admin or scheduled_activity.user_is_sponsor(request.user):
        logger.debug("User has permission to edit")
        edit_perm = True
    else:
        logger.debug("User does not have permission to edit")
        edit_perm = False

    edit_perm_cancelled = False

    if scheduled_activity.cancelled and not request.user.is_eighth_admin:
        logger.debug("Non-admin user does not have permission to edit cancelled activity")
        edit_perm = False
        edit_perm_cancelled = True

    if request.method == "POST":

        if not edit_perm:
            if edit_perm_cancelled:
                return render(request, "error/403.html",
                              {"reason": "You do not have permission to take attendance for this activity. The activity was cancelled."}, status=403)
            else:
                return render(request, "error/403.html",
                              {"reason": "You do not have permission to take attendance for this activity. You are not a sponsor."}, status=403)

        if "admin" in request.path:
            url_name = "eighth_admin_take_attendance"
        else:
            url_name = "eighth_take_attendance"

        if "clear_attendance_bit" in request.POST:
            scheduled_activity.attendance_taken = False
            scheduled_activity.save()
            invalidate_obj(scheduled_activity)

            messages.success(request, "Attendance bit cleared for {}".format(scheduled_activity))

            redirect_url = reverse(url_name, args=[scheduled_activity.id])

            if "no_attendance" in request.GET:
                redirect_url += "?no_attendance={}".format(request.GET["no_attendance"])

            return redirect(redirect_url)

        if not scheduled_activity.block.locked and not request.user.is_eighth_admin:
            return render(request, "error/403.html",
                          {"reason":
                           "You do not have permission to take attendance for this activity. The block has not been locked yet."}, status=403)

        if not scheduled_activity.block.locked and request.user.is_eighth_admin:
            messages.success(request, "Note: Taking attendance on an unlocked block.")

        present_user_ids = list(request.POST.keys())

        csrf = "csrfmiddlewaretoken"
        if csrf in present_user_ids:
            present_user_ids.remove(csrf)

        absent_signups = (EighthSignup.objects.filter(scheduled_activity=scheduled_activity).exclude(user__in=present_user_ids))
        absent_signups.update(was_absent=True)

        for s in absent_signups:
            invalidate_obj(s)

        present_signups = (EighthSignup.objects.filter(scheduled_activity=scheduled_activity, user__in=present_user_ids))
        present_signups.update(was_absent=False)

        for s in present_signups:
            invalidate_obj(s)

        passes = (EighthSignup.objects.filter(scheduled_activity=scheduled_activity, after_deadline=True, pass_accepted=False))
        passes.update(was_absent=True)

        for s in passes:
            invalidate_obj(s)

        scheduled_activity.attendance_taken = True
        scheduled_activity.save()
        invalidate_obj(scheduled_activity)

        messages.success(request, "Attendance updated.")

        redirect_url = reverse(url_name, args=[scheduled_activity.id])

        if "no_attendance" in request.GET:
            redirect_url += "?no_attendance={}".format(request.GET["no_attendance"])

        return redirect(redirect_url)
    else:
        passes = (EighthSignup.objects.select_related("user").filter(scheduled_activity=scheduled_activity, after_deadline=True,
                                                                     pass_accepted=False))

        users = scheduled_activity.members.exclude(eighthsignup__in=passes)
        members = []

        absent_user_ids = (EighthSignup.objects.select_related("user").filter(scheduled_activity=scheduled_activity, was_absent=True).values_list(
            "user__id", flat=True))

        pass_users = (EighthSignup.objects.select_related("user").filter(scheduled_activity=scheduled_activity, after_deadline=True,
                                                                         pass_accepted=True).values_list("user__id", flat=True))

        for user in users:
            members.append({
                "id": user.id,
                "name": user.last_first,  # includes nickname
                "grade": user.grade.number if user.grade else None,
                "present": (scheduled_activity.attendance_taken and (user.id not in absent_user_ids)),
                "had_pass": user.id in pass_users,
                "pass_present": (not scheduled_activity.attendance_taken and user.id in pass_users and user.id not in absent_user_ids),
                "email": user.tj_email
            })
            invalidate_obj(user)

        members.sort(key=lambda m: m["name"])

        context = {
            "scheduled_activity": scheduled_activity,
            "passes": passes,
            "members": members,
            "p": pass_users,
            "no_edit_perm": not edit_perm,
            "edit_perm_cancelled": edit_perm_cancelled,
            "show_checkboxes": (scheduled_activity.block.locked or request.user.is_eighth_admin),
            "show_icons": (scheduled_activity.block.locked and scheduled_activity.block.attendance_locked() and not request.user.is_eighth_admin)
        }

        if request.user.is_eighth_admin:
            context["scheduled_activities"] = (EighthScheduledActivity.objects.filter(block__id=scheduled_activity.block.id))
            logger.debug(context["scheduled_activities"])
            context["blocks"] = (EighthBlock.objects
                                 # .filter(date__gte=get_start_date(request))
                                            .order_by("date"))

        if request.resolver_match.url_name == "eighth_admin_export_attendance_csv":
            response = http.HttpResponse(content_type="text/csv")
            response["Content-Disposition"] = "attachment; filename=\"attendance.csv\""

            writer = csv.writer(response)
            writer.writerow(["Block", "Activity", "Name", "Student ID", "Grade", "Email", "Locked", "Rooms", "Sponsors", "Attendance Taken",
                             "Present", "Had Pass"])
            for member in members:
                row = []
                logger.debug(member)
                row.append(str(scheduled_activity.block))
                row.append(str(scheduled_activity.activity))
                row.append(member["name"])
                row.append(member["id"])
                row.append(member["grade"])
                row.append(member["email"])
                row.append(scheduled_activity.block.locked)
                rooms = scheduled_activity.get_true_rooms()
                row.append(", ".join(["{} ({})".format(room.name, room.capacity) for room in rooms]))
                sponsors = scheduled_activity.get_true_sponsors()
                row.append(" ,".join([sponsor.name for sponsor in sponsors]))
                row.append(scheduled_activity.attendance_taken)
                row.append(member["present"] if scheduled_activity.block.locked else "N/A")

                row.append(member["had_pass"] if scheduled_activity.block.locked else "N/A")
                writer.writerow(row)

            return response
        else:
            return render(request, "eighth/take_attendance.html", context)

Example 48

Project: ion
Source File: signup.py
View license
@login_required
def eighth_signup_view(request, block_id=None):

    if block_id is None and "block" in request.GET:
        block_ids = request.GET.getlist("block")
        if len(block_ids) > 1:
            return redirect("/eighth/signup/multi?{}".format(request.META['QUERY_STRING']))

        block_id = request.GET.get("block")
        args = ""
        if "user" in request.GET:
            args = "user={}".format(request.GET.get("user"))
        return redirect("/eighth/signup/{}?{}".format(block_id, args))

    if request.method == "POST":
        if "unsignup" in request.POST and "aid" not in request.POST:
            uid = request.POST.get("uid")
            bid = request.POST.get("bid")
            force = request.POST.get("force")
            if force == "true":
                force = True
            else:
                force = False

            try:
                user = User.get_user(id=uid)
            except User.DoesNotExist:
                return http.HttpResponseNotFound("Given user does not exist.")

            try:
                eighth_signup = (EighthSignup.objects.get(scheduled_activity__block__id=bid, user__id=uid))
                success_message = eighth_signup.remove_signup(request.user, force)
            except EighthSignup.DoesNotExist:
                return http.HttpResponse("The signup did not exist.")
            except SignupException as e:
                show_admin_messages = (request.user.is_eighth_admin and not request.user.is_student)
                return e.as_response(admin=show_admin_messages)

            return http.HttpResponse(success_message)

        for field in ("uid", "bid", "aid"):
            if not (field in request.POST and request.POST[field].isdigit()):
                return http.HttpResponseBadRequest(field + " must be an " "integer")

        uid = request.POST["uid"]
        bid = request.POST["bid"]
        aid = request.POST["aid"]

        try:
            user = User.get_user(id=uid)
        except User.DoesNotExist:
            return http.HttpResponseNotFound("Given user does not exist.")

        try:
            scheduled_activity = (EighthScheduledActivity.objects.exclude(activity__deleted=True).exclude(cancelled=True).get(block=bid,
                                                                                                                              activity=aid))

        except EighthScheduledActivity.DoesNotExist:
            return http.HttpResponseNotFound("Given activity not scheduled " "for given block.")

        try:
            success_message = scheduled_activity.add_user(user, request)
        except SignupException as e:
            show_admin_messages = (request.user.is_eighth_admin and not request.user.is_student)
            return e.as_response(admin=show_admin_messages)

        return http.HttpResponse(success_message)
    else:
        if block_id is None:
            next_block = EighthBlock.objects.get_first_upcoming_block()
            if next_block is not None:
                block_id = next_block.id
            else:
                last_block = EighthBlock.objects.order_by("date").last()
                if last_block is not None:
                    block_id = last_block.id

        if "user" in request.GET and request.user.is_eighth_admin:
            try:
                user = User.get_user(id=request.GET["user"])
            except (User.DoesNotExist, ValueError):
                raise http.Http404
        else:
            if request.user.is_student:
                user = request.user
            else:
                return redirect("eighth_admin_dashboard")

        try:
            block = (EighthBlock.objects.prefetch_related("eighthscheduledactivity_set").get(id=block_id))
        except EighthBlock.DoesNotExist:
            if EighthBlock.objects.count() == 0:
                # No blocks have been added yet
                return render(request, "eighth/signup.html", {"no_blocks": True})
            else:
                # The provided block_id is invalid
                raise http.Http404

        surrounding_blocks = block.get_surrounding_blocks()
        schedule = []

        signups = EighthSignup.objects.filter(user=user).select_related("scheduled_activity__block", "scheduled_activity__activity")
        block_signup_map = {s.scheduled_activity.block.id: s.scheduled_activity for s in signups}

        for b in surrounding_blocks:
            info = {
                "id": b.id,
                "title": b,
                "block_letter": b.block_letter,
                "block_letter_width": (len(b.block_letter) - 1) * 6 + 15,
                "current_signup": getattr(
                    block_signup_map.get(b.id, {}), "activity", None),
                "current_signup_cancelled": getattr(
                    block_signup_map.get(b.id, {}), "cancelled", False),
                "locked": b.locked
            }

            if len(schedule) and schedule[-1]["date"] == b.date:
                schedule[-1]["blocks"].append(info)
            else:
                day = {}
                day["date"] = b.date
                day["blocks"] = []
                day["blocks"].append(info)
                schedule.append(day)

        serializer_context = {"request": request, "user": user}
        block_info = EighthBlockDetailSerializer(block, context=serializer_context).data
        block_info["schedule"] = schedule

        try:
            active_block_current_signup = block_signup_map[int(block_id)].activity.id
        except KeyError:
            active_block_current_signup = None

        context = {
            "user": user,
            "real_user": request.user,
            "block_info": block_info,
            "activities_list": safe_json(block_info["activities"]),
            "active_block": block,
            "active_block_current_signup": active_block_current_signup
        }

        return render(request, "eighth/signup.html", context)

Example 49

Project: ion
Source File: signup.py
View license
@login_required
def eighth_multi_signup_view(request):
    if request.method == "POST":
        if "unsignup" in request.POST and "aid" not in request.POST:
            uid = request.POST.get("uid")
            bids_comma = request.POST.get("bid")
            force = request.POST.get("force")
            if force == "true":
                force = True
            else:
                force = False

            bids = bids_comma.split(",")

            try:
                user = User.get_user(id=uid)
            except User.DoesNotExist:
                return http.HttpResponseNotFound("Given user does not exist.")

            display_messages = []
            status = 200
            for bid in bids:
                try:
                    btxt = EighthBlock.objects.get(id=bid).short_text
                except EighthBlock.DoesNotExist:
                    return http.HttpResponse("{}: Block did not exist.".format(bid), status=403)
                except ValueError:
                    return http.HttpResponse("{}: Invalid block ID.".format(bid), status=403)

                try:
                    eighth_signup = (EighthSignup.objects.get(scheduled_activity__block__id=bid, user__id=uid))
                    success_message = eighth_signup.remove_signup(request.user, force)
                except EighthSignup.DoesNotExist:
                    status = 403
                    display_messages.append("{}: Signup did not exist.".format(btxt))

                except SignupException as e:
                    show_admin_messages = (request.user.is_eighth_admin and not request.user.is_student)
                    resp = e.as_response(admin=show_admin_messages)
                    status = 403
                    display_messages.append("{}: {}".format(btxt, resp.content))

                except Exception:
                    display_messages.append("{}: Unknown error.".format(btxt))

                else:
                    display_messages.append("{}: {}".format(btxt, success_message))

            return http.HttpResponse("\n".join(display_messages), status=status)

        for field in ("uid", "aid"):
            if not (field in request.POST and request.POST[field].isdigit()):
                return http.HttpResponseBadRequest(field + " must be an " "integer")

        uid = request.POST["uid"]
        bids_comma = request.POST["bid"]
        aid = request.POST["aid"]

        bids = bids_comma.split(",")

        try:
            user = User.get_user(id=uid)
        except User.DoesNotExist:
            return http.HttpResponseNotFound("Given user does not exist.")

        display_messages = []
        status = 200
        for bid in bids:
            try:
                btxt = EighthBlock.objects.get(id=bid).short_text
            except EighthBlock.DoesNotExist:
                return http.HttpResponse("{}: Block did not exist.".format(bid), status=403)
            try:
                scheduled_activity = (EighthScheduledActivity.objects.exclude(activity__deleted=True).exclude(cancelled=True).get(block=bid,
                                                                                                                                  activity=aid))

            except EighthScheduledActivity.DoesNotExist:
                display_messages.append("{}: Activity was not scheduled " "for block".format(btxt))
            else:
                try:
                    success_message = scheduled_activity.add_user(user, request)
                except SignupException as e:
                    show_admin_messages = (request.user.is_eighth_admin and not request.user.is_student)
                    resp = e.as_response(admin=show_admin_messages)
                    status = 403
                    display_messages.append("{}: {}".format(btxt, resp.content))
                else:
                    display_messages.append("{}: {}".format(btxt, success_message))

        return http.HttpResponse("<br />".join(display_messages), status=status)
    else:
        if "user" in request.GET and request.user.is_eighth_admin:
            try:
                user = User.get_user(id=request.GET["user"])
            except (User.DoesNotExist, ValueError):
                raise http.Http404
        else:
            if request.user.is_student:
                user = request.user
            else:
                return redirect("eighth_admin_dashboard")

        block_ids = request.GET.getlist("block")
        try:
            blocks = EighthBlock.objects.select_related().filter(id__in=block_ids)
        except EighthBlock.DoesNotExist:
            raise http.Http404

        serializer_context = {"request": request, "user": user}
        blocks_info = []
        block_signups = []
        activities = {}
        for block in blocks:
            try:
                signup = EighthSignup.objects.get(user=user, scheduled_activity__block=block)
            except EighthSignup.DoesNotExist:
                signup = False

            block_signups.append({"block": block, "signup": signup})

            block_info = EighthBlockDetailSerializer(block, context=serializer_context).data
            blocks_info.append(block_info)
            acts = block_info["activities"]
            for a in acts:
                info = {"id": block.id,
                        "date": block.date,
                        "date_text": block.date.strftime('%a, %b %-d, %Y'),
                        "block_letter": block.block_letter,
                        "short_text": block.short_text}
                if a in activities:
                    activities[a]["blocks"].append(info)
                else:
                    activities[a] = acts[a]
                    activities[a]["blocks"] = [info]
                    activities[a]["total_num_blocks"] = len(blocks)

        # logger.debug(activities)
        context = {
            "user": user,
            "profile_user": user,
            "real_user": request.user,
            "activities_list": safe_json(activities),
            "blocks": blocks,
            "block_signups": block_signups,
            "show_eighth_profile_link": True
        }

        return render(request, "eighth/multi_signup.html", context)

Example 50

Project: ion
Source File: views.py
View license
@login_required
def files_type(request, fstype=None):
    """Do all processing (directory listing, file downloads) for a given filesystem."""
    try:
        host = Host.objects.get(code=fstype)
    except Host.DoesNotExist:
        messages.error(request, "Could not find host in database.")
        return redirect("files")

    if host.available_to_all:
        pass
    elif not host.visible_to(request.user):
        messages.error(
            request, "You don't have permission to access this host.")
        return redirect("files")

    authinfo = get_authinfo(request)

    if not authinfo:
        return redirect("{}?next={}".format(reverse("files_auth"), request.get_full_path()))

    try:
        sftp = create_session(
            host.address, authinfo["username"], authinfo["password"])
    except exceptions as e:
        messages.error(request, e)
        error_msg = str(e).lower()
        if "authentication" in error_msg:
            return redirect("files_auth")
        return redirect("files")
    finally:
        # Delete the stored credentials, so they aren't mistakenly used or
        # accessed later.
        del authinfo

    if host.directory:
        host_dir = host.directory
        if "{}" in host_dir:
            host_dir = host_dir.format(request.user.username)
        if "{win}" in host_dir:
            host_dir = windows_dir_format(host_dir, request.user)
            try:
                sftp.chdir(host_dir)
            except exceptions as e:
                if "NoSuchFile" in "{}".format(e):
                    host_dir = "/"
                    try:
                        sftp.chdir(host_dir)
                    except exceptions as e2:
                        messages.error(request, e)
                        messages.error(
                            request, "Root directory: {}".format(e2))
                        return redirect("files")
                    else:
                        messages.error(
                            request, "Unable to access home folder -- showing root directory instead.")
                else:
                    messages.error(request, e)
                    return redirect("files")
        else:
            try:
                sftp.chdir(host_dir)
            except exceptions as e:
                messages.error(request, e)
                return redirect("files")

    default_dir = normpath(sftp.pwd)

    def can_access_path(fsdir):
        return normpath(fsdir).startswith(default_dir)

    if "file" in request.GET:
        # Download file
        filepath = request.GET.get("file")
        filepath = normpath(filepath)
        filebase = os.path.basename(filepath)
        filebase_escaped = ".".join([slugify(x) for x in filebase.split(".")])
        if can_access_path(filepath):
            try:
                fstat = sftp.stat(filepath)
            except exceptions as e:
                messages.error(
                    request, "Unable to access {}: {}".format(filebase, e))
                return redirect("/files/{}?dir={}".format(fstype, os.path.dirname(filepath)))

            if fstat.st_size > settings.FILES_MAX_DOWNLOAD_SIZE:
                messages.error(request, "Too large to download (>200MB)")
                return redirect("/files/{}?dir={}".format(fstype, os.path.dirname(filepath)))

            tmpfile = tempfile.TemporaryFile(
                prefix="ion_filecenter_{}_{}".format(request.user.username, filebase_escaped))
            logger.debug(tmpfile)

            try:
                sftp.getfo(filepath, tmpfile)
            except exceptions as e:
                messages.error(request, e)
                return redirect("/files/{}?dir={}".format(fstype, os.path.dirname(filepath)))

            content_len = tmpfile.tell()
            tmpfile.seek(0)
            chunk_size = 8192
            response = StreamingHttpResponse(
                FileWrapper(tmpfile, chunk_size), content_type="application/octet-stream")
            response['Content-Length'] = content_len
            response[
                "Content-Disposition"] = "attachment; filename={}".format(filebase_escaped)
            return response

    fsdir = request.GET.get("dir")
    if fsdir:
        fsdir = normpath(fsdir)
        if can_access_path(fsdir):
            try:
                sftp.chdir(fsdir)
            except exceptions as e:
                messages.error(request, e)
                return redirect("files")
        else:
            messages.error(
                request, "Access to the path you provided is restricted.")
            return redirect("/files/{}/?dir={}".format(fstype, default_dir))

    if "zip" in request.GET:
        dirbase_escaped = os.path.basename(fsdir)
        dirbase_escaped = slugify(dirbase_escaped)
        tmpfile = tempfile.TemporaryFile(
            prefix="ion_filecenter_{}_{}".format(request.user.username, dirbase_escaped))

        with tempfile.TemporaryDirectory(prefix="ion_filecenter_{}_{}_zip".format(request.user.username, dirbase_escaped)) as tmpdir:
            remote_directories = [fsdir]
            totalsize = 0
            while remote_directories:
                rd = remote_directories.pop()
                try:
                    remotelist = sftp.listdir(rd)
                except PermissionError as e:
                    logger.debug("Exception %s on %s" % (e, rd))
                    continue
                for item in remotelist:
                    itempath = os.path.join(rd, item)
                    try:
                        fstat = sftp.stat(itempath)
                    except exceptions as e:
                        logger.debug("Could not read %s: %s" % (item, e))
                        continue

                    if stat.S_ISDIR(fstat.st_mode):
                        remote_directories.append(itempath)
                        continue

                    totalsize += fstat.st_size
                    if totalsize > settings.FILES_MAX_DOWNLOAD_SIZE:
                        messages.error(
                            request, "Too large to download (>200MB)")
                        return redirect("/files/{}?dir={}".format(fstype, os.path.dirname(fsdir)))

                    try:
                        localpath = os.path.join(
                            tmpdir, os.path.relpath(rd, fsdir))
                        if not os.path.exists(localpath):
                            os.makedirs(localpath)
                        fh = open(os.path.join(localpath, item), "wb")
                        sftp.getfo(itempath, fh)
                    except exceptions as e:
                        logger.debug("Exception %s on %s" % (e, item))
                        continue

            with zipfile.ZipFile(tmpfile, "w", zipfile.ZIP_DEFLATED) as zf:
                for root, dirs, files in os.walk(tmpdir):
                    for f in files:
                        zf.write(
                            os.path.join(root, f), os.path.join(os.path.relpath(root, tmpdir), f))

        content_len = tmpfile.tell()
        tmpfile.seek(0)
        chunk_size = 8192
        response = StreamingHttpResponse(
            FileWrapper(tmpfile, chunk_size), content_type="application/octet-stream")
        response["Content-Length"] = content_len
        if not dirbase_escaped:
            dirbase_escaped = "files"
        response[
            "Content-Disposition"] = "attachment; filename={}".format(dirbase_escaped + ".zip")
        return response

    try:
        listdir = sftp.listdir()
    except exceptions as e:
        messages.error(request, e)
        listdir = []
    files = []
    for f in listdir:
        if not f.startswith("."):
            try:
                fstat = sftp.stat(f)
            except exceptions:
                # If we can't stat the file, don't show it
                continue
            files.append({
                "name": f,
                "folder": sftp.isdir(f),
                "stat": fstat,
                "stat_mtime": datetime.datetime.fromtimestamp(int(fstat.st_mtime or 0)),
                "too_big": fstat.st_size > settings.FILES_MAX_DOWNLOAD_SIZE
            })

    logger.debug(files)

    current_dir = normpath(sftp.pwd)  # current directory
    dir_list = current_dir.split("/")
    if len(dir_list) > 1 and len(dir_list[-1]) == 0:
        dir_list.pop()
    parent_dir = "/".join(dir_list[:-1])

    if len(parent_dir) == 0:
        parent_dir = "/"

    files = sorted(files, key=lambda f: (not f["folder"], f["name"]))

    context = {
        "host": host,
        "files": files,
        "current_dir": current_dir,
        "parent_dir": parent_dir if can_access_path(parent_dir) else None,
        "max_download_mb": (settings.FILES_MAX_DOWNLOAD_SIZE / 1024 / 1024)
    }

    return render(request, "files/directory.html", context)