django.shortcuts.redirect

Here are the examples of the python api django.shortcuts.redirect 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 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(user=None, 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"]
            # 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, "symposion/proposals/proposal_speaker_manage.html", ctx)

Example 2

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 3

Project: OwnTube
Source File: views.py
View license
@login_required(login_url='/login/')
def submit(request):
    ''' The view for uploading the videos. Only authenticated users can upload videos!
    If we use transloadit to encode the videos we use the more or less official python
    "API" to ask transloadit to transcode our files otherwise we use django tasks to make
    a new task task for encoding this video. If we use bittorrent to distribute our files
    we also use django tasks to make the .torrent files (this can take a few minutes for
    very large files '''
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = VideoForm(request.POST, request.FILES or None)
            if form.is_valid():
                    cmodel = form.save()
                    if cmodel.originalFile:
                        if settings.USE_TRANLOADIT:
                            client = Client(settings.TRANSLOAD_AUTH_KEY, settings.TRANSLOAD_AUTH_SECRET)
                            params = None
                            if (cmodel.kind==0):
                                params = {
                                    'steps': {
                                        ':original': {
                                            'robot': '/http/import',
                                            'url': cmodel.originalFile.url,
                                        }
                                    },
                                    'template_id': settings.TRANSLOAD_TEMPLATE_VIDEO_ID,
                                    'notify_url': settings.TRANSLOAD_NOTIFY_URL
                                }
                            if (cmodel.kind==1):
                                params = {
                                    'steps': {
                                        ':original': {
                                            'robot': '/http/import',
                                            'url': cmodel.originalFile.url,
                                        }
                                    },
                                    'template_id': settings.TRANSLOAD_TEMPLATE_AUDIO_ID,
                                    'notify_url': settings.TRANSLOAD_NOTIFY_URL
                                }
                            if (cmodel.kind==2):
                                params = {
                                    'steps': {
                                        ':original': {
                                            'robot': '/http/import',
                                            'url': cmodel.originalFile.url,
                                        }
                                    },
                                    'template_id': settings.TRANSLOAD_TEMPLATE_VIDEO_AUDIO_ID,
                                    'notify_url': settings.TRANSLOAD_NOTIFY_URL
                                }
                            result = client.request(**params)
                            cmodel.assemblyid = result['assembly_id']
                            cmodel.published = cmodel.autoPublish
                            cmodel.encodingDone = False
                            cmodel.save()
                        else:
                            cmodel.save()
                            djangotasks.register_task(cmodel.encode_media, "Encode the files using ffmpeg")
                            encoding_task = djangotasks.task_for_object(cmodel.encode_media)
                            djangotasks.run_task(encoding_task)
                    if settings.USE_BITTORRENT:
                        djangotasks.register_task(cmodel.create_bittorrent, "Create Bittorrent file for video and serve it")
                        torrent_task = djangotasks.task_for_object(cmodel.create_bittorrent)
                        djangotasks.run_task(torrent_task)
                    cmodel.user = request.user
                    cmodel.save()
                    return redirect(list)
    
            return render_to_response('videos/submit.html',
                                    {'submit_form': form},
                                    context_instance=RequestContext(request))
        else:
            form = VideoForm()
            return render_to_response('videos/submit.html',
                                    {'submit_form': form},
                                    context_instance=RequestContext(request))
    else:
        return render_to_response('videos/nothing.html',
                            context_instance=RequestContext(request))

Example 4

Project: builder
Source File: account.py
View license
def accountSignup(request):
  """Django handler for user signup."""

  # If the feature is disabled
  if not settings.SIGNUP_ENABLED:
    return redirect('/')

  def getRedirect():
    """Helper to get redirect."""
    redirectUrl = request.GET.get('redirect', '/home')

    if redirectUrl != 'payment':
      return redirect(redirectUrl)

    coupon = request.GET.get('c', None)
    if coupon:
      return redirect('/payment?c='+coupon)

    return redirect('/payment')

  if request.method == 'GET':
    if not request.user.is_authenticated():
      signupForm = SignupForm(initial=request.GET)
      return render(request, 'signup.tmpl', dictionary={
        'signup_form': signupForm
      })
    else:
      return getRedirect()

  if request.method == 'POST':
    # check to make sure plan is filled out ok
    signupForm = SignupForm(request.REQUEST)
    if not signupForm.is_valid():
      return render(request, 'signup.tmpl', dictionary={
        'signup_form': signupForm,
        'error':       'invalid'
      })

    # set up required fields
    success = handleSignup(request, signupForm.cleaned_data)

    if not success:
      # form is validated, but we have failed to create new user.
      return render(request, 'signup.tmpl', dictionary={
        'signup_form': signupForm,
        'error':       'unknown'
      })

    # new user successfullly created.
    return getRedirect()

Example 5

Project: vumi-go
Source File: views.py
View license
@login_required
def details(request):
    token_manager = DjangoTokenManager(request.user_api.api.token_manager)
    account = request.user_api.get_user_account()
    account_form = AccountForm(request.user, initial={
        'name': request.user.first_name,
        'surname': request.user.last_name,
        'email_address': request.user.email,
        'msisdn': account.msisdn,
        'confirm_start_conversation': account.confirm_start_conversation,
        'email_summary': account.email_summary,
    })
    email_form = EmailForm()
    password_change_form = PasswordChangeForm(request.user)

    if request.method == 'POST':
        if '_account' in request.POST:
            account_form = AccountForm(request.user, request.POST)
            if account_form.is_valid():

                data = account_form.cleaned_data
                params = {
                    'first_name': data['name'],
                    'last_name': data['surname'],
                    'email_address': data['email_address'],
                    'msisdn': data['msisdn'],
                    'email_summary': data['email_summary'],
                    'confirm_start_conversation':
                        data['confirm_start_conversation'],
                }

                token = token_manager.generate_callback_token(request.path,
                    'Your details are being updated', update_account_details,
                    callback_args=(request.user.id,),
                    callback_kwargs=params, user_id=request.user.id)

                context = params.copy()
                context.update({
                    'token_url': token_manager.url_for_token(token),
                    })

                send_mail(
                    'Vumi Go account detail change confirmation',
                    render_to_string(
                        'account/change_account_details_mail.txt',
                        context),
                    settings.DEFAULT_FROM_EMAIL,
                    [request.user.email, '[email protected]'])

                messages.info(request,
                    'Please confirm this change by clicking on the link '
                    'that was just sent to your mailbox.')
                return redirect('account:details')

        elif '_email' in request.POST:
            email_form = EmailForm(request.POST)
            if email_form.is_valid():
                subject = email_form.cleaned_data['subject']
                message = email_form.cleaned_data['message']
                _from = request.user.email
                send_mail(subject, message, _from, ['[email protected]'])
                messages.info(request, 'Thanks for your email. We will be in '
                                        'touch shortly.')
                return redirect(reverse('account:details'))
            else:
                messages.error(request, 'We didn\'t understand some of the '
                    'values your provided in the email form, please try '
                    'again.')

        elif '_password' in request.POST:
            password_change_form = PasswordChangeForm(request.user,
                                                      request.POST)
            if password_change_form.is_valid():
                password_change_form.save()

    return render(request, 'account/details.html', {
        'email_form': email_form,
        'account_form': account_form,
        'password_change_form': password_change_form,
        'account_key': request.user_api.user_account_key,
    })

Example 6

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 7

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 8

Project: pretix
Source File: middleware.py
View license
    def process_request(self, request):
        url = resolve(request.path_info)
        url_name = url.url_name
        if not request.path.startswith(get_script_prefix() + 'control'):
            # This middleware should only touch the /control subpath
            return
        if hasattr(request, 'organizer'):
            # If the user is on a organizer's subdomain, he should be redirected to pretix
            return redirect(urljoin(settings.SITE_URL, request.get_full_path()))
        if url_name in self.EXCEPTIONS:
            return
        if not request.user.is_authenticated:
            # Taken from django/contrib/auth/decorators.py
            path = request.build_absolute_uri()
            # urlparse chokes on lazy objects in Python 3, force to str
            resolved_login_url = force_str(
                resolve_url(settings.LOGIN_URL_CONTROL))
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login

            return redirect_to_login(
                path, resolved_login_url, REDIRECT_FIELD_NAME)

        request.user.events_cache = request.user.events.order_by(
            "organizer", "date_from").prefetch_related("organizer")
        if 'event' in url.kwargs and 'organizer' in url.kwargs:
            try:
                request.event = Event.objects.filter(
                    slug=url.kwargs['event'],
                    permitted__id__exact=request.user.id,
                    organizer__slug=url.kwargs['organizer'],
                ).select_related('organizer')[0]
                request.eventperm = EventPermission.objects.get(
                    event=request.event,
                    user=request.user
                )
                request.organizer = request.event.organizer
            except IndexError:
                raise Http404(_("The selected event was not found or you "
                                "have no permission to administrate it."))
        elif 'organizer' in url.kwargs:
            try:
                request.organizer = Organizer.objects.filter(
                    slug=url.kwargs['organizer'],
                    permitted__id__exact=request.user.id,
                )[0]
            except IndexError:
                raise Http404(_("The selected organizer was not found or you "
                                "have no permission to administrate it."))

Example 9

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 10

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 11

Project: pyconapac-2016
Source File: views.py
View license
@login_required
def payment_process(request):
    if request.method == 'GET':
        return redirect('registration_index')

    # alreay registered
    if Registration.objects.filter(user=request.user, payment_status__in=['paid','ready']).exists():
        return redirect('registration_status')

    payment_logger.debug(request.POST)
    form = RegistrationAdditionalPriceForm(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 JsonResponse({
            'success': False,
            'message': form_errors_string,  # TODO : ...
        })

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

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

    if form.cleaned_data.get('additional_price', 0) < 0:
        return JsonResponse({
            'success': False,
            'message': u'후원 금액은 0원 이상이어야 합니다.',
        })

    registration = Registration(
            user=request.user,
            name = form.cleaned_data.get('name'),
            email = request.user.email,
            additional_price = form.cleaned_data.get('additional_price', 0),
            company = form.cleaned_data.get('company', ''),
            phone_number = form.cleaned_data.get('phone_number', ''),
            merchant_uid = request.POST.get('merchant_uid'),
            option = form.cleaned_data.get('option'),
            payment_method = form.cleaned_data.get('payment_method')
        )

    # sold out
    if registration.option.is_soldout:
        return JsonResponse({
            'success': False,
            'message': u'{name} 티켓이 매진 되었습니다'.format(name=registration.option.name),
        })

    try:
        product = registration.option

        if registration.payment_method == 'card':
            access_token = get_access_token(config.IMP_API_KEY, config.IMP_API_SECRET)
            imp_client = Iamporter(access_token)
            # TODO : use validated and cleaned data
            imp_params = dict(
                token=request.POST.get('token'),
                merchant_uid=request.POST.get('merchant_uid'),
                amount=product.price + registration.additional_price,
                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'),
                name=product.name,
                buyer_name=request.POST.get('name'),
                buyer_email=request.POST.get('email'),
                buyer_tel=request.POST.get('phone_number')

            )
            if request.POST.get('birth') == '':
                # foreign payment
                imp_client.foreign(**imp_params)
            else:
                imp_client.foreign(**imp_params)
                # imp_client.onetime(**imp_params)
            confirm = imp_client.find_by_merchant_uid(request.POST.get('merchant_uid'))

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

            registration.transaction_code = confirm.get('pg_tid')
            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()
        elif registration.payment_method == 'bank':
            registration.transaction_code = request.POST.get('pg_tid')
            registration.payment_method = request.POST.get('pay_method')
            registration.payment_status = request.POST.get('status')
            registration.payment_message = request.POST.get('fail_reason')
            registration.vbank_name = request.POST.get('vbank_name', None)
            registration.vbank_num = request.POST.get('vbank_num', None)
            registration.vbank_date = request.POST.get('vbank_date', None)
            registration.vbank_holder = request.POST.get('vbank_holder', None)
            registration.save()
        else:
            raise Exception('Unknown payment method')

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

Example 12

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 13

Project: qualitio
Source File: views.py
View license
    def post(self, *args, **kwargs):
        payment_form = PaymentForm(self.request.POST)
        if payment_form.is_valid():
            payment_strategy = Strategy.objects.get(
                name=payment_form.cleaned_data['plan']
            )
            payment = self.request.organization.payment
            
            paypal_data = dict(payment_form.cleaned_data, **{
                "CURRENCYCODE": "USD",
                "PROFILESTARTDATE": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
                "DESC": "%s:%s" % (self.request.organization.name, payment_strategy.name),
                "BILLINGPERIOD": "Month",
                "BILLINGFREQUENCY": "1",
                "AMT": payment_strategy.price,
                "PAYERSTATUS": "verified",
            })
            paypal_data['FIRSTNAME'] = "%s : %s" % (
                self.request.organization.name,
                paypal_data['FIRSTNAME']
            )
            
            paypal = PayPal()

            try:
                paypal.ManageRecurringPaymentsProfileStatus(
                    PROFILEID=payment.paypal_id,
                    ACTION="Cancel"
                )
            except PayPalException as e:
                if e.message['L_ERRORCODE0'] != '11556': 
                    raise e

            try:
                paypal_response = paypal.CreateRecurringPaymentsProfile(**paypal_data)
            except PayPalException as e:
                return self.render_to_response(
                    self.get_context_data(
                        payment_form=payment_form,
                        payment_error=e.message['L_LONGMESSAGE0']
                    )
                )
                    
            valid_time = datetime.now() + relativedelta(months=+1, days=+1)

            old_strategy = payment.strategy
            
            payment.strategy = payment_strategy
            payment.valid_time = valid_time
            payment.paypal_id = paypal_response['PROFILEID']
            payment.status = Profile.PENDING
            
            payment.save()
            
            send_mail(
                'Qualitio Project, Payment profile updated for %s organization'
                % self.request.organization.name,
                render_to_string('payments/profile_update.mail',
                                 {"organization": self.request.organization,
                                  "old_strategy": old_strategy,
                                  "current_strategy": payment.strategy}),
                'Qualitio Notifications <[email protected]>',
                self.request.organization.admins.values_list("email", flat=True))

            return redirect("/settings/billing/")

Example 14

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 15

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 16

Project: Misago
Source File: list.py
View license
    def dispatch(self, request, *args, **kwargs):
        mass_actions_list = self.mass_actions or []
        extra_actions_list = self.extra_actions or []

        refresh_querystring = False

        context = {
            'items': self.get_queryset(),

            'paginator': None,
            'page': None,

            'order_by': [],
            'order': None,

            'search_form': None,
            'active_filters': {},

            'querystring': '',
            'query_order': {},
            'query_filters': {},

            'selected_items': [],
            'selection_label': self.selection_label,
            'empty_selection_label': self.empty_selection_label,
            'mass_actions': mass_actions_list,

            'extra_actions': extra_actions_list,
            'extra_actions_len': len(extra_actions_list),
        }

        if request.method == 'POST' and mass_actions_list:
            try:
                response = self.handle_mass_action(request, context)
                if response:
                    return response
                else:
                    return redirect(request.path)
            except MassActionError as e:
                messages.error(request, e.args[0])

        if self.ordering:
            ordering_methods = self.get_ordering_methods(request)
            used_method = self.get_ordering_method_to_use(ordering_methods)
            self.set_ordering_in_context(context, used_method)

            if (ordering_methods['GET'] and
                    ordering_methods['GET'] != ordering_methods['session']):
                # Store GET ordering in session for future requests
                session_key = self.ordering_session_key
                request.session[session_key] = ordering_methods['GET']

            if context['order_by'] and not ordering_methods['GET']:
                # Make view redirect to itself with querystring,
                # So address ball contains copy-friendly link
                refresh_querystring = True

        SearchForm = self.get_search_form(request)
        if SearchForm:
            filtering_methods = self.get_filtering_methods(request)
            active_filters = self.get_filtering_method_to_use(
                filtering_methods)
            if request.GET.get('clear_filters'):
                # Clear filters from querystring
                request.session.pop(self.filters_session_key, None)
                active_filters = {}
            self.apply_filtering_on_context(
                context, active_filters, SearchForm)

            if (filtering_methods['GET'] and
                    filtering_methods['GET'] != filtering_methods['session']):
                # Store GET filters in session for future requests
                session_key = self.filters_session_key
                request.session[session_key] = filtering_methods['GET']
            if request.GET.get('set_filters'):
                # Force store filters in session
                session_key = self.filters_session_key
                request.session[session_key] = context['active_filters']
                refresh_querystring = True

            if context['active_filters'] and not filtering_methods['GET']:
                # Make view redirect to itself with querystring,
                # So address ball contains copy-friendly link
                refresh_querystring = True

        self.make_querystrings(context)

        if self.items_per_page:
            try:
                self.paginate_items(context, kwargs.get('page', 0))
            except EmptyPage:
                return redirect(
                    '%s%s' % (reverse(self.root_link), context['querystring']))

        if refresh_querystring:
            return redirect('%s%s' % (request.path, context['querystring']))

        return self.render(request, context)

Example 17

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 18

Project: classic.rhizome.org
Source File: views.py
View license
@login_required
def proposal_edit(request, proposal_id):
    proposal = get_object_or_404(Proposal, pk=proposal_id)
    user = request.user
    proposal_form = ProposalForm(initial={'author':request.user})
    other_artists_list = None
    today = datetime.datetime.now()

    if proposal.get_artists():
        other_artists_list = ', '.join(['%s' % artist.email for artist in proposal.get_artists()])

    proposal_form = ProposalForm(request.POST or None, request.FILES or None, \
            instance=proposal.id and Proposal.objects.get(id=proposal.id ), \
            initial={'other_artists_users':other_artists_list })

    if request.method == 'POST':
        proposal_form = ProposalForm(request.POST or None, request.FILES or None, \
                instance=proposal.id and Proposal.objects.get(id=proposal.id ), \
                initial={'other_artists_users':str(other_artists_list) })

        if proposal_form.is_valid():
            user.first_name = request.POST['first_name']
            user.last_name = request.POST['last_name']
            user.save()

            proposal = proposal_form.save(commit=False)

            if request.POST['status'] == 'delete':
                proposal.delete()
                return HttpResponseRedirect('%s?deleted=True' % reverse('commissions_index'))

            proposal.author = user
            proposal.email = user.email
            proposal.username = user.get_full_name()

            # verification of artist accounts for m2m is handled via the form
            cleaned_user_list = proposal_form.cleaned_data['other_artists_users']

            if cleaned_user_list:
                for user in cleaned_user_list:
                    proposal.artists.add(user)

            proposal.save()

            if proposal.image:
                # create_thumbnails uses saved image
                proposal.thumbnail = create_thumbnail(proposal.image)

            if request.POST['status'] == 'preview':
                proposal.save()
                return redirect('commissions_proposal_preview', proposal_id=proposal.id)

            elif request.POST['status'] == 'save':
                proposal.save()
                return HttpResponseRedirect('%s?save=True' % reverse('commissions_proposal_edit', args=[proposal.id]))

            elif request.POST['status'] == 'publish':
                proposal.submitted = 1
                proposal.save()
                proposal.send_published_proposal_notification_email()
                return HttpResponseRedirect('%s?thanks=True' % reverse('commissions_proposal_detail', args=[proposal.id]))
        else:
            proposal_form = ProposalForm(request.POST,request.FILES or None, initial={'author':request.user})

    if request.user == proposal.author \
        and today > proposal.cycle.submission_start_date \
        and today < proposal.cycle.submission_end_date:
        return render_to_response('commissions/submit.html', {'proposal_form':proposal_form, 'cycle':proposal.cycle}, RequestContext(request))
    else:
        return redirect('commissions_index')

Example 19

Project: django-classifieds
Source File: browse.py
View license
def search_results(request, slug):
    category = get_object_or_404(Category, slug=slug)
    fields = list(category.field_set.all())
    fields += list(Field.objects.filter(category=None))
    fieldsLeft = [field.name for field in fields]

    if request.method == "POST" or 'search' in request.session:
        ads = category.ad_set.filter(active=True,
                                     expires_on__gt=datetime.datetime.now())
        # A request dictionary with keys defined for all
        # fields in the category.
        post = {}
        if 'search' in request.session:
            post.update(request.session['search'])
        else:
            post.update(request.POST)

        sforms = prepare_sforms(fields, fieldsLeft, post)

        isValid = True

        for f in sforms:
            # TODO: this assumes the form is not required
            # (it's a search form after all)
            if not f.is_valid() and not f.is_empty():
                isValid = False

        if isValid:
            if request.method == 'POST':
                request.session['search'] = {}
                request.session['search'].update(request.POST)
                return redirect('classifieds_browse_search_results', slug=slug)

            for f in sforms:
                ads = f.filter(ads)

            if ads.count() == 0:
                return render_to_response('classifieds/list.html',
                                          {'no_results': True,
                                           'category': category},
                                          context_instance=RequestContext(request))
            else:
                context = context_sortable(request, ads)
                context['category'] = category
                return render_to_response('classifieds/list.html', context,
                                          context_instance=RequestContext(request))
    else:
        sforms = prepare_sforms(fields, fieldsLeft)

    return render_to_response('classifieds/search.html',
                              {'forms': sforms, 'category': category},
                              context_instance=RequestContext(request))

Example 20

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 21

Project: coursys
Source File: views.py
View license
def view_page(request, course_slug, page_label):
    offering = get_object_or_404(CourseOffering, slug=course_slug)
    pages = Page.objects.filter(offering=offering, label=page_label)
    if not pages:
        # missing page: do something more clever than the standard 404
        member = _check_allowed(request, offering, offering.page_creators()) # users who can create pages
        can_create = bool(member)
        context = {'offering': offering, 'can_create': can_create, 'page_label': page_label}
        return render(request, 'pages/missing_page.html', context, status=404)
    else:
        page = pages[0]

    version = page.current_version()
    
    member = _check_allowed(request, offering, page.can_read, page.releasedate())
    # check that we have an allowed member of the course (and can continue)
    if not member:
        if _check_allowed(request, offering, page.can_read, None):
            # would be allowed without the date restriction: report that nicely
            context = {'offering': offering, 'page_label': page_label, 'releasedate': page.releasedate(),
                       'page_label': page.label}
            return render(request, 'pages/unreleased_page.html', context, status=403)

        return _forbidden_response(request, page.get_can_read_display())

    if request.user.is_authenticated():
        editor = _check_allowed(request, offering, page.can_write, page.editdate())
        can_edit = bool(editor)
    else:
        can_edit = False

    redirect_url = None
    if ( 'migrated_to' in page.config
            and offering.config.get('redirect_pages', False)
            and not page.config.get('prevent_redirect', False) ):
        # we have a migrated page and should redirect to the new location
        slug, label = page.config['migrated_to']
        url = reverse(view_page, kwargs={'course_slug': slug, 'page_label': label})

        member = _check_allowed(request, offering, offering.page_creators()) # users who can create pages
        can_create = bool(member)
        if can_create:
            # show these users a message so they can see what's happening
            redirect_url = url
        else:
            # but most users just get a 301
            return redirect(url, permanent=True)

    if version.redirect:
        # this is a redirection stub: honour it.
        url = urljoin(page.get_absolute_url(), version.redirect)
        member = _check_allowed(request, offering, offering.page_creators())  # users who can create pages
        can_create = bool(member)
        if can_create:
            # show these users a message so they can see what's happening
            redirect_url = url
        else:
            # but most users just get a 301/410
            resp = redirect(url, permanent=True)
            if version.redirect_reason() == 'delete':
                resp.status_code = 410
            return resp

    is_index = page_label=='Index'
    if is_index:
        # canonical-ize the index URL
        url = reverse(index_page, kwargs={'course_slug': course_slug})
        if request.path != url:
            return HttpResponseRedirect(url)
    
    context = {'offering': offering, 'page': page, 'version': version,
               'can_edit': can_edit, 'is_index': is_index, 'redirect_url': redirect_url}
    return render(request, 'pages/view_page.html', context)

Example 22

Project: oioioi
Source File: views.py
View license
@menu_registry.register_decorator(_("Ranking"), lambda request:
        reverse('default_ranking', kwargs={'contest_id': request.contest.id}),
    order=440)
@enforce_condition(contest_exists & can_enter_contest)
@enforce_condition(has_any_ranking_visible,
                   template='rankings/no_rankings.html')
def ranking_view(request, key=None):
    rcontroller = request.contest.controller.ranking_controller()
    choices = rcontroller.available_rankings(request)
    if key is None:
        key = choices[0][0]
    if key not in zip(*choices)[0]:
        raise Http404

    context = dict()

    ranking = None

    if rcontroller.can_search_for_users():
        form = FilterUsersInRankingForm(request, request.GET)
        context['form'] = form

        if form.is_valid():
            user = form.cleaned_data.get('user')
            # Everybody can search for themselves.
            # Contest admins can search for anyone.
            if user and (is_contest_admin(request) or user == request.user):
                found_pos = rcontroller.find_user_position(request, key, user)
                if found_pos:
                    users_per_page = getattr(settings, 'PARTICIPANTS_ON_PAGE',
                                             100)
                    found_page = ((found_pos - 1) // users_per_page) + 1
                    get_dict = request.GET.copy()
                    get_dict.pop('user')
                    get_dict['page'] = found_page
                    return redirect(request.path + '?' + get_dict.urlencode()
                            + '#' + str(user.id))
                else:
                    msg = _("User is not in the ranking.")
                    form._errors['user'] = form.error_class([msg])

    if ranking is None:
        # Changing request.GET is necessary!
        # The pagination library not only truncates the list of objects,
        # but also generates the links to other pages.
        # It simply copies the current url and replaces 'page'
        # with another number. If there is a different GET parameter,
        # it is included (without any change) in the url to another page.

        # If a user requests a page, he can provide any number of useless
        # GET parameters, which will be shown in urls to other pages.
        # The ranking page could be cached and those urls could be
        # visible to other users, giving them links to the ranking
        # with strange arguments (e.g. arguments, which perform a search).

        # Below, only 'user' key is deleted, because that's the only argument
        # performing an action, and I'd like to change request.GET
        # as less as possible.
        # This solution does not prevent users from sending "messages"
        # between each other (using these GET parameters).
        request.GET = request.GET.copy()
        try:
            request.GET.pop('user')
        except KeyError:
            pass
        ranking = rcontroller.get_rendered_ranking(request, key)

    context['choices'] = choices
    context['ranking'] = ranking
    context['key'] = key

    return TemplateResponse(request, 'rankings/ranking_view.html', context)

Example 23

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

    AttachmentFormset = inlineformset_factory(Problem, ProblemAttachment,
                                              extra=0, form=AttachmentForm,
                                              can_delete=True)

    TagFormset = modelformset_factory(Tag, form=TagForm, extra=0,
                                      can_delete=True)

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

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

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

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

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

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

            pif.save()
            test_formset.save()
            return redirect(reverse('problem_settings', kwargs={
                'problem_instance_id': problem_instance_id}))

        test_forms = test_formset
        pi_form = pif

    else:
        test_forms = TestFormset(queryset=tests)
        pi_form = PIFormset(queryset=ProblemInstance.objects.filter(id=pi.id),
                            prefix='pif')
        attachment_formset = AttachmentFormset(queryset=attachments,
                                               prefix='attachment',
                                               instance=p)
        tag_formset = TagFormset(prefix='tag', queryset=tags)

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

    for attachment_form in attachment_formset.forms:
        attachment_form.update_link(request.contest.id)
    context['attachment_formset'] = attachment_formset
    context['tag_formset'] = tag_formset

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

Example 24

Project: SmartElect
Source File: screens.py
View license
    def post(self, request, *args, **kwargs):
        """
        If the input is valid, this method will always:

        * End the current screen
        * Save the case and screen objects
        * Start the next screen
        * Return a redirect

        If outcome is non-None, it will set the case outcome.

        If next view is None, it will end the case and redirect to help_desk home.

        If the SUBMIT button was pressed, check the form. If valid, call form.update_case(case).
        If not valid, display the form and any errors that were found.

        Otherwise, it redirects to the next view.
        """
        if self.screen:
            # make sure we're in the right view
            if self.screen.name != self.name:
                messages.info(request, _('Redirecting to current screen for this case.'))
                return redirect(reverse(self.screen.name, args=[self.case.pk]))
        else:
            return HttpResponseServerError("Case has no current screen")
        self.button_name = None
        for name, value in request.POST.iteritems():
            if name.startswith("button_"):
                self.button_name = name[7:]
                break
        if not self.button_name:
            return HttpResponseBadRequest()
        if self.button_name == BUTTON_HUNG_UP:
            # FIXME: Here, should we just end the case right away and redirect back home?
            self.button = {
                'next_view': HUNG_UP,
                'outcome': Case.HUNG_UP,
            }
        elif self.button_name in [BUTTON_GO_BACK, BUTTON_START_OVER]:
            self.button = {}
        elif self.button_name not in self.buttons:
            return HttpResponseBadRequest()
        else:
            self.button = self.buttons[self.button_name]
        assert hasattr(self, 'button')
        if self.button_name == BUTTON_SUBMIT and self.form_class:
            self.form = self.form_class(request.POST)
            if not self.form.is_valid():
                return self.get(request, *args, **kwargs)
            self.form.update_case(self.case)
        if self.button_name == BUTTON_START_OVER:
            # Special case - reset everything
            self.case.reset()
            self.case.current_screen = ScreenRecord.objects.create(case=self.case,
                                                                   name=FIRST_SCREEN)
            self.case.save()
            return redirect(reverse(FIRST_SCREEN, args=[self.case.pk]))
        if self.button_name == BUTTON_GO_BACK:
            # Special case
            # Delete the current screen
            self.case.current_screen.delete()
            # The new "last" screen is the one we want to end up on.
            # What's its name?
            last_screen = self.case.last_screen
            if last_screen:
                screen_name = last_screen.name
            else:
                return HttpResponseBadRequest()
            # Delete previous screen too, so we can do it again from scratch
            self.case.last_screen.delete()
            self.case.start_screen(screen_name)
            # If this was a screen with a form, undo any data previously input from this form
            view = view_for_screen[screen_name]
            if view.form_class:
                view.form_class().undo(self.case)
            # Clear any outcome we might have reached
            self.case.call_outcome = None
            self.case.save()
            return redirect(screen_name, self.case.pk)

        # screen.end will save the screen and case for us
        self.screen.end(case=self.case, button=self.button_name)
        next_view = self.button['next_view']
        if callable(next_view):
            next_view = next_view(self.case)
        outcome = self.button.get('outcome', None)
        if outcome:
            self.case.call_outcome = outcome
            self.case.save()
        if next_view is None:
            assert self.case.call_outcome
            self.case.end()
            self.case.save()
            messages.info(request, _('The call has ended.'))
            return redirect('help_desk_home')
        else:
            self.case.start_screen(next_view)
            return redirect(next_view, self.case.pk)

Example 25

Project: froide
Source File: views.py
View license
def make_request(request, public_body=None, public_body_id=None):
    if public_body_id is not None:
        public_body = get_object_or_404(PublicBody,
                pk=int(public_body_id))
        url = reverse('foirequest-make_request', kwargs={
            'public_body': public_body.slug
        })
        # Keep the query string for subject, body intact on redirect
        return redirect('%s?%s' % (url, request.META['QUERY_STRING']),
                        permanent=True)

    public_body_form = 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()
        public_body_form = PublicBodyForm()
    initial = {
        "subject": request.GET.get('subject', ''),
        "reference": request.GET.get('ref', ''),
        "redirect_url": request.GET.get('redirect', '')
    }
    if 'body' in request.GET:
        initial['body'] = request.GET['body']

    if 'hide_public' in request.GET:
        initial['hide_public'] = True
        initial['public'] = False

    if 'hide_similar' in request.GET:
        initial['hide_similar'] = True

    initial['jurisdiction'] = request.GET.get("jurisdiction", None)
    public_body_search = request.GET.get("topic", "")
    initial['public_body_search'] = public_body_search

    default_law = FoiLaw.get_default_law(public_body)
    if default_law is None:
        messages.add_message(request, messages.INFO,
            _('You need to setup a default FOI Law object'))
        return render(request, '500.html')

    rq_form = RequestForm(user=request.user, list_of_laws=all_laws,
                          default_law=default_law, initial=initial)

    user_form = None
    if not request.user.is_authenticated:
        initial_user_data = {}
        if 'email' in request.GET:
            initial_user_data['user_email'] = request.GET['email']
        if 'first_name' in request.GET:
            initial_user_data['first_name'] = request.GET['first_name']
        if 'last_name' in request.GET:
            initial_user_data['last_name'] = request.GET['last_name']
        user_form = NewUserForm(initial=initial_user_data)

    return render(request, 'foirequest/request.html', {
        "public_body": public_body,
        "public_body_form": public_body_form,
        "request_form": rq_form,
        "user_form": user_form,
        "public_body_search": public_body_search
    })

Example 26

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 27

Project: cartridge
Source File: views.py
View license
@never_cache
def checkout_steps(request, form_class=OrderForm, extra_context=None):
    """
    Display the order form and handle processing of each step.
    """

    # Do the authentication check here rather than using standard
    # login_required decorator. This means we can check for a custom
    # LOGIN_URL and fall back to our own login view.
    authenticated = request.user.is_authenticated()
    if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated:
        url = "%s?next=%s" % (settings.LOGIN_URL, reverse("shop_checkout"))
        return redirect(url)

    try:
        settings.SHOP_CHECKOUT_FORM_CLASS
    except AttributeError:
        pass
    else:
        from warnings import warn
        warn("The SHOP_CHECKOUT_FORM_CLASS setting is deprecated - please "
             "define your own urlpattern for the checkout_steps view, "
             "passing in your own form_class argument.")
        form_class = import_dotted_path(settings.SHOP_CHECKOUT_FORM_CLASS)

    initial = checkout.initial_order_data(request, form_class)
    step = int(request.POST.get("step", None) or
               initial.get("step", None) or
               checkout.CHECKOUT_STEP_FIRST)
    form = form_class(request, step, initial=initial)
    data = request.POST
    checkout_errors = []

    if request.POST.get("back") is not None:
        # Back button in the form was pressed - load the order form
        # for the previous step and maintain the field values entered.
        step -= 1
        form = form_class(request, step, initial=initial)
    elif request.method == "POST" and request.cart.has_items():
        form = form_class(request, step, initial=initial, data=data)
        if form.is_valid():
            # Copy the current form fields to the session so that
            # they're maintained if the customer leaves the checkout
            # process, but remove sensitive fields from the session
            # such as the credit card fields so that they're never
            # stored anywhere.
            request.session["order"] = dict(form.cleaned_data)
            sensitive_card_fields = ("card_number", "card_expiry_month",
                                     "card_expiry_year", "card_ccv")
            for field in sensitive_card_fields:
                if field in request.session["order"]:
                    del request.session["order"][field]

            # FIRST CHECKOUT STEP - handle discount code. This needs to
            # be set before shipping, to allow for free shipping to be
            # first set by a discount code.
            if step == checkout.CHECKOUT_STEP_FIRST:
                form.set_discount()

            # ALL STEPS - run billing/tax handlers. These are run on
            # all steps, since all fields (such as address fields) are
            # posted on each step, even as hidden inputs when not
            # visible in the current step.
            try:
                billship_handler(request, form)
                tax_handler(request, form)
            except checkout.CheckoutError as e:
                checkout_errors.append(e)

            # FINAL CHECKOUT STEP - run payment handler and process order.
            if step == checkout.CHECKOUT_STEP_LAST and not checkout_errors:
                # Create and save the initial order object so that
                # the payment handler has access to all of the order
                # fields. If there is a payment error then delete the
                # order, otherwise remove the cart items from stock
                # and send the order receipt email.
                order = form.save(commit=False)
                order.setup(request)
                # Try payment.
                try:
                    transaction_id = payment_handler(request, form, order)
                except checkout.CheckoutError as e:
                    # Error in payment handler.
                    order.delete()
                    checkout_errors.append(e)
                    if settings.SHOP_CHECKOUT_STEPS_CONFIRMATION:
                        step -= 1
                else:
                    # Finalize order - ``order.complete()`` performs
                    # final cleanup of session and cart.
                    # ``order_handler()`` can be defined by the
                    # developer to implement custom order processing.
                    # Then send the order email to the customer.
                    order.transaction_id = transaction_id
                    order.complete(request)
                    order_handler(request, form, order)
                    checkout.send_order_email(request, order)
                    # Set the cookie for remembering address details
                    # if the "remember" checkbox was checked.
                    response = redirect("shop_complete")
                    if form.cleaned_data.get("remember"):
                        remembered = "%s:%s" % (sign(order.key), order.key)
                        set_cookie(response, "remember", remembered,
                                   secure=request.is_secure())
                    else:
                        response.delete_cookie("remember")
                    return response

            # If any checkout errors, assign them to a new form and
            # re-run is_valid. If valid, then set form to the next step.
            form = form_class(request, step, initial=initial, data=data,
                              errors=checkout_errors)
            if form.is_valid():
                step += 1
                form = form_class(request, step, initial=initial)

    # Update the step so that we don't rely on POST data to take us back to
    # the same point in the checkout process.
    try:
        request.session["order"]["step"] = step
        request.session.modified = True
    except KeyError:
        pass

    step_vars = checkout.CHECKOUT_STEPS[step - 1]
    template = "shop/%s.html" % step_vars["template"]
    context = {"CHECKOUT_STEP_FIRST": step == checkout.CHECKOUT_STEP_FIRST,
               "CHECKOUT_STEP_LAST": step == checkout.CHECKOUT_STEP_LAST,
               "CHECKOUT_STEP_PAYMENT": (settings.SHOP_PAYMENT_STEP_ENABLED and
                   step == checkout.CHECKOUT_STEP_PAYMENT),
               "step_title": step_vars["title"], "step_url": step_vars["url"],
               "steps": checkout.CHECKOUT_STEPS, "step": step, "form": form}
    context.update(extra_context or {})
    return TemplateResponse(request, template, context)

Example 28

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 29

Project: volontulo
Source File: offers.py
View license
    @staticmethod
    @correct_slug(Offer, 'offers_join', 'title')
    def post(request, slug, id_):  # pylint: disable=unused-argument
        """View responsible for saving join for particular offer."""
        form = OfferApplyForm(request.POST)
        offer = Offer.objects.get(id=id_)
        if form.is_valid():
            if request.user.is_authenticated():
                user = request.user
            else:
                user = User.objects.filter(
                    email=request.POST.get('email')
                ).exists()

                if user:
                    messages.info(
                        request,
                        'Zaloguj się, aby zapisać się do oferty.'
                    )
                    return redirect(
                        reverse('login') + '?next={}'.format(request.path)
                    )
                else:
                    messages.info(
                        request,
                        'Zarejestruj się, aby zapisać się do oferty.'
                    )
                    return redirect('register')

            has_applied = Offer.objects.filter(
                volunteers=user,
                volunteers__offer=id_,
            ).count()
            if has_applied:
                messages.error(
                    request,
                    u'Już wyraziłeś chęć uczestnictwa w tej ofercie.'
                )
                return redirect('offers_list')

            offer.volunteers.add(user)
            offer.save()

            send_mail(
                request,
                'offer_application',
                [
                    user.email,
                    request.POST.get('email'),
                ],
                dict(
                    email=request.POST.get('email'),
                    phone_no=request.POST.get('phone_no'),
                    fullname=request.POST.get('fullname'),
                    comments=request.POST.get('comments'),
                    offer=offer,
                )
            )
            messages.success(
                request,
                u'Zgłoszenie chęci uczestnictwa zostało wysłane.'
            )
            return redirect(
                'offers_view',
                slug=slugify(offer.title),
                id_=offer.id,
            )
        else:
            errors = '<br />'.join(form.errors)
            messages.error(
                request,
                u'Formularz zawiera nieprawidłowe dane' + errors
            )
            volunteer_user = UserProfile()
            if request.user.is_authenticated():
                volunteer_user = request.user.userprofile
            return render(
                request,
                'offers/offer_apply.html',
                {
                    'offer': offer,
                    'form': form,
                    'volunteer_user': volunteer_user,
                }
            )

Example 30

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 31

Project: read_FEC
Source File: views.py
View license
@cache_page(LONG_CACHE_TIME)
def candidate_cycle(request, slug, candidate_id, cycle):
    if not is_valid_four_digit_string_cycle(cycle):
        raise Http404
    
    # figure out which cycles are available. The current one goes first, because it is being displayed.     
    cycles = Candidate_Overlay.objects.filter(fec_id=candidate_id)
    
    candidate_overlay = None
    try:
        candidate_overlay = cycles.get(cycle=cycle)
    except Candidate_Overlay.DoesNotExist:
        if len(cycles) > 0:
            candidate_overlay = cycles.order_by('-cycle')[0]
            return redirect("/candidate/%s/%s/%s/" % (candidate_overlay.cycle, slug, candidate_id))
        else:
            raise Http404
    
    other_cycles = cycles.exclude(cycle=cycle)
    cycle_list = [candidate_overlay] + list(other_cycles)
    cycle_endpoints = get_cycle_endpoints(int(cycle))
        
    title = "%s (%s) (%s cycle)" % (candidate_overlay.name, candidate_overlay.party, cycle)

    authorized_committee_list = Authorized_Candidate_Committees.objects.filter(candidate_id=candidate_id, cycle=cycle)
    committee_list = [x.get('committee_id') for x in authorized_committee_list.values('committee_id')]

    report_list = Committee_Time_Summary.objects.filter(com_id__in=committee_list, coverage_from_date__gte=cycle_endpoints['start'], coverage_through_date__lte=cycle_endpoints['end']).order_by('-coverage_through_date')


    end_of_coverage_date = None
    recent_report_list = None
    if report_list:
        end_of_coverage_date = report_list[0].coverage_through_date


    recent_report_total = 0
    if end_of_coverage_date:
        recent_report_list = new_filing.objects.filter(fec_id__in=committee_list, coverage_from_date__gte=end_of_coverage_date, coverage_to_date__lte=cycle_endpoints['end'], form_type__in=['F6', 'F6A', 'F6N']).exclude(is_superceded=True)
        if recent_report_list:
            recent_report_total = recent_report_list.aggregate(spending_total=Sum('tot_raised'))['spending_total']

    else:
        recent_report_list = new_filing.objects.filter(fec_id__in=committee_list, coverage_from_date__gte=cycle_endpoints['start'], coverage_to_date__lte=cycle_endpoints['end'], form_type__in=['F6', 'F6A', 'F6N']).exclude(is_superceded=True)


    # are their outside groups who've spent for/against this candidate? 
    outside_spenders = Pac_Candidate.objects.filter(candidate=candidate_overlay, cycle=cycle,  total_ind_exp__gte=1000).select_related('committee')

    recent_ies = None
    if outside_spenders:
        recent_ies = SkedE.objects.filter(candidate_checked=candidate_overlay, expenditure_amount__gte=5000, superceded_by_amendment=False, expenditure_date_formatted__gte=cycle_endpoints['start'], expenditure_date_formatted__lte=cycle_endpoints['end'] ).select_related('candidate_checked').order_by('-expenditure_date_formatted')[:10]



    return render_to_response('datapages/candidate.html',
        {
        'title':title,
        'report_list':report_list,
        'candidate':candidate_overlay,
        'authorized_committee_list':authorized_committee_list,
        'outside_spenders':outside_spenders,
        'recent_report_list':recent_report_list,
        'recent_ies':recent_ies,
        'recent_report_total':recent_report_total,
        'cycle_list':cycle_list,
        'current_cycle':cycle
        }, 
        context_instance=RequestContext(request)
    )

Example 32

Project: syndicate
Source File: views.py
View license
@authenticate
def create(request):
    '''
    View to handle creation of AG's
    '''
    session = request.session
    username = session['login_email']
    user = db.read_user( username )

    # Helper method used to simplify error-handling. When fields are entered incorrectly,
    # a session message is set and this method is called.
    def give_create_form(username, session):
        message = session.pop('message', "")
        form = gatewayforms.CreateAG()
        t = loader.get_template('gateway_templates/create_acquisition_gateway.html')
        c = RequestContext(request, {'username':username,'form':form, 'message':message})
        return HttpResponse(t.render(c))

    if request.POST:
        # Validate input forms
        form = gatewayforms.CreateAG(request.POST, request.FILES)
        if form.is_valid():
            kwargs = {}

            # Try and load JSON config file/data, if present. First check uploaded files, then
            # the text box.
            if "json_config" in request.FILES:
                if request.FILES['json_config'].multiple_chunks():
                    session['message'] = "Uploaded file too large; please make smaller than 2.5M"
                    return give_create_form(username, session)
                config = request.FILES['json_config'].read()
                try:
                    kwargs['json_config'] = json.loads(config)
                except Exception as e:
                    logging.info("Possible JSON load error: %s" % e)
                    try:
                        kwargs['json_config'] = json.loads("\"" + config + "\"")
                    except Exception as e:
                        logging.error("Definite JSON load error %s" % e)
                        session['message'] = "Error parsing given JSON text."
                        return give_create_form(username, session)

            # No upload, check text box.
            elif "json_config_text" in form.cleaned_data:
                try:
                    kwargs['json_config'] = json.loads(form.cleaned_data['json_config_text'])
                except Exception as e:
                    logging.info("Possible JSON load error: %s" % e)
                    try:
                        kwargs['json_config'] = json.loads("\"" + str(form.cleaned_data['json_config_text']) + "\"")
                    except Exception as e:
                        logging.error("Definite JSON load error %s" % e)
                        session['message'] = "Error parsing given JSON text."
                        return give_create_form(username, session)


            try:
                kwargs['ms_username'] = form.cleaned_data['g_name']
                kwargs['port'] = form.cleaned_data['port']
                kwargs['host'] = form.cleaned_data['host']
                kwargs['ms_password'] = form.cleaned_data['g_password']
                new_ag = db.create_acquisition_gateway(user, **kwargs)
            except Exception as E:
                session['message'] = "AG creation error: %s" % E
                return give_create_form(username, session)

            session['new_change'] = "Your new gateway is ready."
            session['next_url'] = '/syn/AG/allgateways'
            session['next_message'] = "Click here to see your acquisition gateways."
            return redirect('/syn/thanks/')
        else:
            # Prep returned form values (so they don't have to re-enter stuff)

            if 'g_name' in form.errors:
                oldname = ""
            else:
                oldname = request.POST['g_name']
            if 'host' in form.errors:
                oldhost = ""
            else:
                oldhost = request.POST['host']
            if 'port' in form.errors:
                oldport = ""
            else:
                oldport = request.POST['port']
            oldjson = request.POST['json_config_text']
            # Prep error message
            message = "Invalid form entry: "

            for k, v in form.errors.items():
                message = message + "\"" + k + "\"" + " -> " 
                for m in v:
                    message = message + m + " "

            # Give them the form again
            form = gatewayforms.CreateAG(initial={'g_name': oldname,
                                       'host': oldhost,
                                       'port': oldport,
                                       'json_config_text':oldjson,
                                       })
            t = loader.get_template('gateway_templates/create_acquisition_gateway.html')
            c = RequestContext(request, {'username':username,'form':form, 'message':message})
            return HttpResponse(t.render(c))

    else:
        # Not a POST, give them blank form
        return give_create_form(username, session)

Example 33

Project: syndicate
Source File: decorators.py
View license
def precheck(g_type, redirect_view):

    '''
    Wrapper function to simplify verifying existence of gateways
    and correct passwords when modifying gateways in all gateway views.

    All wrappend functions need to take the following args:

    + g_type is the type of gateway, either 'AG' 'UG' or 'RG'
    + redirect_view is the location to be redirected

    - request
    - g_id
    '''

    # Three decorator types

    def ag_gateway_precheck(f):

        def ag_wrapper(request, g_id):

            if not request.POST:
                return redirect('django_ag.views.viewgateway', g_id=g_id)

            session = request.session
            username = session['login_email']
            try:
                g = db.read_acquisition_gateway(g_id)
                if not g:
                    raise Exception("No gateway exists.")
            except Exception as e:
                logging.error("Error reading gateway %s : Exception: %s" % (g_id, e))
                message = "No acquisition gateway by the name of %s exists." % g_id
                t = loader.get_template("gateway_templates/viewgateway_failure.html")
                c = Context({'message':message, 'username':username})
                return HttpResponse(t.render(c))

            form = libforms.Password(request.POST)
            if not form.is_valid():
                session['message'] = "Password required."
                return redirect(redirect_view, g_id)
            # Check password hash
            if not AG.authenticate(g, form.cleaned_data['password']):
                session['message'] = "Incorrect password."
                return redirect(redirect_view, g_id)

            return f(request, g_id)

        return ag_wrapper

    def ug_gateway_precheck(f):
        
        def ug_wrapper(request, g_id):
            
            if not request.POST:
                return redirect('django_ug.views.viewgateway', g_id=g_id)

            session = request.session
            username = session['login_email']

            try:
                g = db.read_user_gateway(g_id)
                if not g:
                    raise Exception("No gateway exists.")
            except Exception as e:
                logging.error("Error reading gateway %s : Exception: %s" % (g_id, e))
                message = "No user gateway by the name of %s exists." % g_id
                t = loader.get_template("gateway_templates/viewgateway_failure.html")
                c = Context({'message':message, 'username':username})
                return HttpResponse(t.render(c))

            form = libforms.Password(request.POST)
            if not form.is_valid():
                session['message'] = "Password required."
                return redirect(redirect_view, g_id)
            # Check password hash
            if not UG.authenticate(g, form.cleaned_data['password']):
                session['message'] = "Incorrect password."
                return redirect(redirect_view, g_id)

            return f(request, g_id)

        return ug_wrapper


    def rg_gateway_precheck(f):
        
        def rg_wrapper(request, g_id):
            
            if not request.POST:
                return redirect('django_rg.views.viewgateway', g_id=g_id)

            session = request.session
            username = session['login_email']
            try:
                g = db.read_replica_gateway(g_id)
                if not g:
                    raise Exception("No gateway exists.")
            except Exception as e:
                logging.error("Error reading gateway %s : Exception: %s" % (g_id, e))
                message = "No replica gateway by the name of %s exists." % g_id
                t = loader.get_template("gateway_templates/viewgateway_failure.html")
                c = Context({'message':message, 'username':username})
                return HttpResponse(t.render(c))

            form = libforms.Password(request.POST)
            if not form.is_valid():
                session['message'] = "Password required."
                return redirect(redirect_view, g_id)
            # Check password hash
            if not RG.authenticate(g, form.cleaned_data['password']):
                session['message'] = "Incorrect password."
                return redirect(redirect_view, g_id)

            return f(request, g_id)

        return rg_wrapper


    # Pythonesque case statement to determine what type of decorator to return.

    decorators = {"AG": ag_gateway_precheck,
               "RG": rg_gateway_precheck,
               "UG": ug_gateway_precheck
    }


    # Executed code

    try:
        return decorators[g_type]
    except KeyError:
        logging.error("Gatway type argument %s for decorators.precheck doesn't exist." % g_type)
        return redirect('/syn/home')

Example 34

Project: syndicate
Source File: views.py
View license
@authenticate
def create(request):
    '''
    View to handle creation of RG's
    '''
    session = request.session
    username = session['login_email']
    user = db.read_user( username )

    # Helper method used to simplify error-handling. When fields are entered incorrectly,
    # a session message is set and this method is called.
    def give_create_form(username, session):
        message = session.pop('message', "")
        form = gatewayforms.CreateRG()
        t = loader.get_template('gateway_templates/create_replica_gateway.html')
        c = RequestContext(request, {'username':username,'form':form, 'message':message})
        return HttpResponse(t.render(c))

    if request.POST:
        # Validate input forms
        form = gatewayforms.CreateRG(request.POST, request.FILES)
        if form.is_valid():
            kwargs = {}
            
            # Try and load JSON config file/data, if present. First check uploaded files, then
            # the text box.
            if "json_config" in request.FILES:
                if request.FILES['json_config'].multiple_chunks():
                    session['message'] = "Uploaded file too large; please make smaller than 2.5M"
                    return give_create_form(username, session)
                config = request.FILES['json_config'].read()
                try:
                    kwargs['config'] = json.loads(config)
                except Exception as e:
                    logging.info("Possible JSON load error: %s" % e)
                    try:
                        kwargs['config'] = json.loads("\"" + config + "\"")
                    except Exception as e:
                        logging.error("Definite JSON load error %s" % e)
                        session['message'] = "Error parsing given JSON text."
                        return give_create_form(username, session)

            # No upload, check text-box
            elif "json_config_text" in form.cleaned_data:
                try:
                    kwargs['config'] = json.loads(form.cleaned_data['json_config_text'])
                except Exception as e:
                    logging.info("Possible JSON load error: %s" % e)
                    try:
                        kwargs['config'] = json.loads("\"" + str(form.cleaned_data['json_config_text']) + "\"")
                    except Exception as e:
                        logging.error("Definite JSON load error %s" % e)
                        session['message'] = "Error parsing given JSON text."
                        return give_create_form(username, session)     


            try:
                kwargs['ms_username'] = form.cleaned_data['g_name']
                kwargs['port'] = form.cleaned_data['port']
                kwargs['host'] = form.cleaned_data['host']
                kwargs['ms_password'] = form.cleaned_data['g_password']
                kwargs['private'] = form.cleaned_data['private']
                new_RG = db.create_replica_gateway(user, **kwargs)
            except Exception as E:
                session['message'] = "RG creation error: %s" % E
                return give_create_form(username, session)

            session['new_change'] = "Your new gateway is ready."
            session['next_url'] = '/syn/RG/allgateways/'
            session['next_message'] = "Click here to see all replica gateways."
            return redirect('/syn/thanks/')
        else:
            # Prep returned form values (so they don't have to re-enter stuff)
            if 'g_name' in form.errors:
                oldname = ""
            else:
                oldname = request.POST['g_name']
            if 'host' in form.errors:
                oldhost = ""
            else:
                oldhost = request.POST['host']
            if 'port' in form.errors:
                oldport = ""
            else:
                oldport = request.POST['port']
            oldjson = request.POST['json_config_text']

            # Prep error message
            message = "Invalid form entry: "

            for k, v in form.errors.items():
                message = message + "\"" + k + "\"" + " -> " 
                for m in v:
                    message = message + m + " "

            # Give then the form again
            form = gatewayforms.CreateRG(initial={'g_name': oldname,
                                       'host': oldhost,
                                       'port': oldport,
                                       'json_config_text':oldjson,
                                       })
            t = loader.get_template('gateway_templates/create_replica_gateway.html')
            c = RequestContext(request, {'username':username,'form':form, 'message':message})
            return HttpResponse(t.render(c))

    else:
        # Not a POST, give them blank form
        return give_create_form(username, session)

Example 35

Project: syndicate
Source File: views.py
View license
@verifyownership_private
@authenticate
def deletevolume(request, volume_id):
    '''
    View for deleting volumes. Since so many other entites have properties related
    to volume ID's, numerous db updates need to be checked. CQ, they are all grouped
    together into the transactional helper method multi_update().
    '''

    # Clear out volume_id in properties for users, UG's, AG's, and RG's.
    @transactional(xg=True)
    def multi_update(vol, users, usergateways, acquisitiongateways, replicagateways):
        v_id = vol.volume_id
        db.delete_volume(v_id)
        logging.info(users)

        for user in users:
            fields = {}

            if v_id in user.volumes_o:
                new_volumes_o = user.volumes_o
                new_volumes_o.remove(v_id)
                fields['volumes_o'] = new_volumes_o

            if v_id in user.volumes_rw:
                new_volumes_rw = user.volumes_rw
                new_volumes_rw.remove(v_id)
                fields['volumes_rw'] = new_volumes_rw

            if v_id in user.volumes_r:
                new_volumes_r = user.volumes_r
                new_volumes_r.remove(v_id)
                fields['volumes_r'] = new_volumes_r

            if fields:
                db.update_user(user.email, **fields)


        for ug in usergateways:
            fields = {}
            fields['volume_id'] = 0
            db.update_user_gateway(ug.g_id, **fields)

        for ag in acquisitiongateways:
            logging.info(ag)
            fields = {}
            new_ids = ag.volume_ids.remove(v_id)
            if not new_ids:
                fields['volume_ids'] = []
            else:
                fields['volume_ids'] = new_ids
            db.update_acquisition_gateway(ag.g_id, **fields)

        for rg in replicagateways:
            fields = {}
            new_ids = rg.volume_ids.remove(v_id)
            if not new_ids:
                fields['volume_ids'] = []
            else:
                fields['volume_ids'] = new_ids
            db.update_replica_gateway(rg.g_id, **fields)

        # Clear initial data session variable to prevent stale tables in ag.views.viewgateway and rg.views.viewgateway
        session.pop("rg_initial_data" + str(v_id), None)
        session.pop("ag_initial_data" + str(v_id), None)
        # Clear initial data session variable to prevent stale data in volume settings, change rgs, and change ags.
        session.pop("volume_initial_ags" + str(v_id), None)
        session.pop("volume_initial_rgs" + str(v_id), None)

    session = request.session
    message = session.pop('message', "")
    username = session['login_email']
    vol = db.read_volume( volume_id )
    if not vol:
        return redirect('django_volume.views.viewvolume', volume_id)

    if request.method == "POST":
        form = forms.DeleteVolume(request.POST)
        if form.is_valid():
            # Check password hash
            hash_check = Volume.generate_password_hash(form.cleaned_data['password'], vol.volume_secret_salt)
            if hash_check == vol.volume_secret_salted_hash:
                # Ok to delete
                attrs = {}
                users = db.list_users({'SyndicateUser.volumes_rw ==':vol.volume_id})
                users.extend(db.list_users({'SyndicateUser.volumes_r ==':vol.volume_id}))
                ags = db.list_acquisition_gateways_by_volume(vol.volume_id)
                rgs = db.list_replica_gateways_by_volume(vol.volume_id)
                ugs = db.list_user_gateways_by_volume(vol.volume_id)
                try:
                    multi_update(vol, users, ugs, ags, rgs)
                except Exception as e:
                     logging.error("Unable to delete volume %s" % e)
                     session['message'] = "Unable to delete volume."
                     return redirect('django_volume.views.deletevolume', volume_id=vol.volume_id)
                session['new_change'] = "We've deleted your volume."
                session['next_url'] = '/syn/volume/myvolumes/'
                session['next_message'] = "Click here to go back to your volumes."
                return redirect('/syn/thanks')
            else:
                session['message'] = "Invalid password"
                return redirect('django_volume.views.deletevolume', volume_id=vol.volume_id)
        else:
            session['message'] = "Please fill out all entries"
            return redirect('django_volume.views.deletevolume', vol.volume_id)
    else:
        form = forms.DeleteVolume()
        t = loader.get_template('deletevolume.html')
        c = RequestContext(request, {'username':username, 'form':form, 'message':message,'volume':vol} )
        return HttpResponse(t.render(c))    

Example 36

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

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

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

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

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

    event = get_object_or_404(Event, pk=event_id)

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

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

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

    # get available addons
    active_addons = get_active_addons(event)

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

    #custom_reg_form = None

    if custom_reg_form:
        RF = FormForCustomRegForm
    else:
        RF = RegistrantForm

    # start the form set factory
    RegistrantFormSet = formset_factory(
        RF,
        formset=RegistrantBaseFormSet,
        can_delete=True,
        extra=0,
    )

    RegAddonFormSet = formset_factory(
        RegAddonForm,
        formset=RegAddonBaseFormSet,
        extra=0,
    )

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

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

        # This form is just here to preserve the data in case of invalid registrants
        # The real validation of addons is after validation of registrants
        addon_formset = RegAddonFormSet(request.POST,
                            prefix='addon',
                            event=event,
                            extra_params={
                                'addons':active_addons,
                                'valid_addons':active_addons,
                            })
        addon_formset.is_valid()

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

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

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

                EventLog.objects.log(instance=event)

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

    sets = reg_formset.get_sets()

    # build our hidden form dynamically
    hidden_form = None
    if custom_reg_form:
        params = {'prefix': 'registrant',
                  'event': event,
                  'extra_params': {
                        'pricings':event_pricings,
                        'custom_reg_form': custom_reg_form,
                        'event': event
                    }
                  }
        FormSet = formset_factory(
            FormForCustomRegForm,
            formset=RegistrantBaseFormSet,
            can_delete=True,
            extra=1,
        )
        formset = FormSet(**params)
        hidden_form = formset.forms[0]


    return render_to_response(template_name, {
            'event':event,
            'reg_form':reg_form,
            'custom_reg_form': custom_reg_form,
            'hidden_form': hidden_form,
            'registrant': reg_formset,
            'addon_formset': addon_formset,
            'sets': sets,
            'addons':active_addons,
            'pricings':active_pricings,
            'anon_pricing':True,
            'total_price':reg_formset.get_total_price()+addon_formset.get_total_price(),
            'allow_memberid_pricing':get_setting('module', 'events', 'memberidpricing'),
            'shared_pricing':get_setting('module', 'events', 'sharedpricing'),
            }, context_instance=RequestContext(request))

Example 37

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

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

    file = get_object_or_404(File, pk=id)

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

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

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

    # get image binary
    try:
        data = file.file.read()
        file.file.close()
    except IOError:  # no such file or directory
        raise Http404

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

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

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

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

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

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

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

        image.save(response, image.format, **params)

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

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

        return response

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

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

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

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

Example 38

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

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

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

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

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

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

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

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

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

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

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

            if email_copies or email_recipients:
                # prepare attachments
                attachments = []
                try:
                    for f in form_for_form.files.values():
                        f.seek(0)
                        attachments.append((f.name, f.read()))
                except ValueError:
                    attachments = []
                    for field_entry in entry.fields.all():
                        if field_entry.field.field_type == 'FileField':
                            try:
                                f = default_storage.open(field_entry.value)
                            except IOError:
                                pass
                            else:
                                f.seek(0)
                                attachments.append((f.name.split('/')[-1], f.read()))

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

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

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

                if form.recurring_payment:
                    if request.user.is_anonymous():
                        rp_user = entry.creator
                    else:
                        rp_user = request.user
                    billing_start_dt = datetime.datetime.now()
                    trial_period_start_dt = None
                    trial_period_end_dt = None
                    if entry.pricing.has_trial_period:
                        trial_period_start_dt = datetime.datetime.now()
                        trial_period_end_dt = trial_period_start_dt + datetime.timedelta(1)
                        billing_start_dt = trial_period_end_dt
                    # Create recurring payment
                    rp = RecurringPayment(
                             user=rp_user,
                             description=form.title,
                             billing_period=entry.pricing.billing_period,
                             billing_start_dt=billing_start_dt,
                             num_days=entry.pricing.num_days,
                             due_sore=entry.pricing.due_sore,
                             payment_amount=price,
                             taxable=entry.pricing.taxable,
                             tax_rate=entry.pricing.tax_rate,
                             has_trial_period=entry.pricing.has_trial_period,
                             trial_period_start_dt=trial_period_start_dt,
                             trial_period_end_dt=trial_period_end_dt,
                             trial_amount=entry.pricing.trial_amount,
                             creator=rp_user,
                             creator_username=rp_user.username,
                             owner=rp_user,
                             owner_username=rp_user.username,
                         )
                    rp.save()
                    rp.add_customer_profile()

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

                    EventLog.objects.log(instance=form)

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

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

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

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

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

Example 39

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 40

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 41

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 42

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 43

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 44

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)

Example 45

Project: wagtail
Source File: pages.py
View license
def create(request, content_type_app_name, content_type_model_name, parent_page_id):
    parent_page = get_object_or_404(Page, id=parent_page_id).specific
    parent_page_perms = parent_page.permissions_for_user(request.user)
    if not parent_page_perms.can_add_subpage():
        raise PermissionDenied

    try:
        content_type = ContentType.objects.get_by_natural_key(content_type_app_name, content_type_model_name)
    except ContentType.DoesNotExist:
        raise Http404

    # Get class
    page_class = content_type.model_class()

    # Make sure the class is a descendant of Page
    if not issubclass(page_class, Page):
        raise Http404

    # page must be in the list of allowed subpage types for this parent ID
    if page_class not in parent_page.creatable_subpage_models():
        raise PermissionDenied

    if not page_class.can_create_at(parent_page):
        raise PermissionDenied

    for fn in hooks.get_hooks('before_create_page'):
        result = fn(request, parent_page, page_class)
        if hasattr(result, 'status_code'):
            return result

    page = page_class(owner=request.user)
    edit_handler_class = page_class.get_edit_handler()
    form_class = edit_handler_class.get_form_class(page_class)

    next_url = get_valid_next_url_from_request(request)

    if request.method == 'POST':
        form = form_class(request.POST, request.FILES, instance=page,
                          parent_page=parent_page)

        if form.is_valid():
            page = form.save(commit=False)

            is_publishing = bool(request.POST.get('action-publish')) and parent_page_perms.can_publish_subpage()
            is_submitting = bool(request.POST.get('action-submit'))

            if not is_publishing:
                page.live = False

            # Save page
            parent_page.add_child(instance=page)

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()

            # Notifications
            if is_publishing:
                if page.go_live_at and page.go_live_at > timezone.now():
                    messages.success(request, _("Page '{0}' created and scheduled for publishing.").format(page.get_admin_display_title()), buttons=[
                        messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit'))
                    ])
                else:
                    messages.success(request, _("Page '{0}' created and published.").format(page.get_admin_display_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}' created and submitted for moderation.").format(page.get_admin_display_title()),
                    buttons=[
                        messages.button(reverse('wagtailadmin_pages:view_draft', args=(page.id,)), _('View draft')),
                        messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit'))
                    ]
                )
                if not send_notification(page.get_latest_revision().id, 'submitted', request.user.pk):
                    messages.error(request, _("Failed to send notifications to moderators"))
            else:
                messages.success(request, _("Page '{0}' created.").format(page.get_admin_display_title()))

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

            if is_publishing or is_submitting:
                # we're done here
                if next_url:
                    # redirect back to 'next' url if present
                    return redirect(next_url)
                # redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                target_url = reverse('wagtailadmin_pages:edit', args=[page.id])
                if next_url:
                    # Ensure the 'next' url is passed through again if present
                    target_url += '?next=%s' % urlquote(next_url)
                return redirect(target_url)
        else:
            messages.error(request, _("The page could not be created due to validation errors"))
            edit_handler = edit_handler_class(instance=page, form=form)
            has_unsaved_changes = True
    else:
        signals.init_new_page.send(sender=create, page=page, parent=parent_page)
        form = form_class(instance=page)
        edit_handler = edit_handler_class(instance=page, form=form)
        has_unsaved_changes = False

    return render(request, 'wagtailadmin/pages/create.html', {
        'content_type': content_type,
        'page_class': page_class,
        'parent_page': parent_page,
        'edit_handler': edit_handler,
        'preview_modes': page.preview_modes,
        'form': form,
        'next': next_url,
        'has_unsaved_changes': has_unsaved_changes,
    })

Example 46

Project: wagtail
Source File: pages.py
View license
def edit(request, page_id):
    latest_revision = get_object_or_404(Page, id=page_id).get_latest_revision()
    page = get_object_or_404(Page, id=page_id).get_latest_revision_as_page()
    parent = page.get_parent()

    content_type = ContentType.objects.get_for_model(page)
    page_class = content_type.model_class()

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

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

    edit_handler_class = page_class.get_edit_handler()
    form_class = edit_handler_class.get_form_class(page_class)

    next_url = get_valid_next_url_from_request(request)

    errors_debug = None

    if request.method == 'POST':
        form = form_class(request.POST, request.FILES, instance=page,
                          parent_page=parent)

        if form.is_valid() and not page.locked:
            page = form.save(commit=False)

            is_publishing = bool(request.POST.get('action-publish')) and page_perms.can_publish()
            is_submitting = bool(request.POST.get('action-submit'))
            is_reverting = bool(request.POST.get('revision'))

            # If a revision ID was passed in the form, get that revision so its
            # date can be referenced in notification messages
            if is_reverting:
                previous_revision = get_object_or_404(page.revisions, id=request.POST.get('revision'))

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()
                # Need to reload the page because the URL may have changed, and we
                # need the up-to-date URL for the "View Live" button.
                page = page.specific_class.objects.get(pk=page.pk)

            # Notifications
            if is_publishing:
                if page.go_live_at and page.go_live_at > timezone.now():
                    # Page has been scheduled for publishing in the future

                    if is_reverting:
                        message = _(
                            "Revision from {0} of page '{1}' has been scheduled for publishing."
                        ).format(
                            previous_revision.created_at.strftime("%d %b %Y %H:%M"),
                            page.get_admin_display_title()
                        )
                    else:
                        message = _(
                            "Page '{0}' has been scheduled for publishing."
                        ).format(
                            page.get_admin_display_title()
                        )

                    messages.success(request, message, buttons=[
                        messages.button(
                            reverse('wagtailadmin_pages:edit', args=(page.id,)),
                            _('Edit')
                        )
                    ])

                else:
                    # Page is being published now

                    if is_reverting:
                        message = _(
                            "Revision from {0} of page '{1}' has been published."
                        ).format(
                            previous_revision.created_at.strftime("%d %b %Y %H:%M"),
                            page.get_admin_display_title()
                        )
                    else:
                        message = _(
                            "Page '{0}' has been published."
                        ).format(
                            page.get_admin_display_title()
                        )

                    messages.success(request, message, buttons=[
                        messages.button(
                            page.url,
                            _('View live')
                        ),
                        messages.button(
                            reverse('wagtailadmin_pages:edit', args=(page_id,)),
                            _('Edit')
                        )
                    ])

            elif is_submitting:

                message = _(
                    "Page '{0}' has been submitted for moderation."
                ).format(
                    page.get_admin_display_title()
                )

                messages.success(request, message, buttons=[
                    messages.button(
                        reverse('wagtailadmin_pages:view_draft', args=(page_id,)),
                        _('View draft')
                    ),
                    messages.button(
                        reverse('wagtailadmin_pages:edit', args=(page_id,)),
                        _('Edit')
                    )
                ])

                if not send_notification(page.get_latest_revision().id, 'submitted', request.user.pk):
                    messages.error(request, _("Failed to send notifications to moderators"))

            else:  # Saving

                if is_reverting:
                    message = _(
                        "Page '{0}' has been replaced with revision from {1}."
                    ).format(
                        page.get_admin_display_title(),
                        previous_revision.created_at.strftime("%d %b %Y %H:%M")
                    )
                else:
                    message = _(
                        "Page '{0}' has been updated."
                    ).format(
                        page.get_admin_display_title()
                    )

                messages.success(request, message)

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

            if is_publishing or is_submitting:
                # we're done here - redirect back to the explorer
                if next_url:
                    # redirect back to 'next' url if present
                    return redirect(next_url)
                # redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                target_url = reverse('wagtailadmin_pages:edit', args=[page.id])
                if next_url:
                    # Ensure the 'next' url is passed through again if present
                    target_url += '?next=%s' % urlquote(next_url)
                return redirect(target_url)
        else:
            if page.locked:
                messages.error(request, _("The page could not be saved as it is locked"))
            else:
                messages.error(request, _("The page could not be saved due to validation errors"))

            edit_handler = edit_handler_class(instance=page, form=form)
            errors_debug = (
                repr(edit_handler.form.errors) +
                repr([
                    (name, formset.errors)
                    for (name, formset) in edit_handler.form.formsets.items()
                    if formset.errors
                ])
            )
            has_unsaved_changes = True
    else:
        form = form_class(instance=page)
        edit_handler = edit_handler_class(instance=page, form=form)
        has_unsaved_changes = False

    # Check for revisions still undergoing moderation and warn
    if latest_revision and latest_revision.submitted_for_moderation:
        messages.warning(request, _("This page is currently awaiting moderation"))

    return render(request, 'wagtailadmin/pages/edit.html', {
        'page': page,
        'content_type': content_type,
        'edit_handler': edit_handler,
        'errors_debug': errors_debug,
        'preview_modes': page.preview_modes,
        'form': form,
        'next': next_url,
        'has_unsaved_changes': has_unsaved_changes,
    })

Example 47

Project: django-urli18n
Source File: middleware.py
View license
    def process_request(self, request):
        """Process the request of according to following conditions:
        
        - Only processes ``GET`` request, since others will not be displayed in the address bar anyway
        - Only processes ``GET`` request for url path's (as regular expressions) which are provided in ``URLI18N_INCLUDE_PATHS`` setting. If a path is provided in ``URLI18N_INCLUDE_PATHS`` setting it will transform the url, for all others the url will not be transformed (though the language will be changed)
        - If the url path does not start with a language prefix and it will build a new url from given path and redirect to it 
        - If ``URLI18N_ALWAYS_SHOW_LANGUAGE`` setting is set to True (the default) it will always show the language prefix in the url, if  ``URLI18N_ALWAYS_SHOW_LANGUAGE`` setting is set to False it will show the language prefix only for languages which are not the default language (set via the django setting for ``LANGUAGE_CODE``)
        - If url path starts with a valid language prefix it will render the view attached to the given url in the original url conf. If will resolve other middleware classes ``process_request`` and ``process_view`` calls first to avoid conflicts
        - If user is not navigating on the page but coming from a source which is not the domain of this project it will change the language directly when provided in the url or if not provided use the current activated language (given by process_request of django.middleware.locale.LocaleMiddleware)
        
        Args:
            - ``request``: the django request object to process
            
        Returns:
            - Either a redirect response to the right path with leading language shortcut or the view response for the view attached to the url of the path
        """
        if request.method == 'GET':
            path = request.path
            full_path = request.get_full_path()
            language = translation.get_language()
            host = request.get_host()
            redirect_to = None
            regex_ref = re.compile('^http[s]?://%s' % host, re.UNICODE)
            referer = request.META.get('HTTP_REFERER', None)
            language_shortcuts = [lang[0] for lang in settings.LANGUAGES]
            if utils.is_included_path(path) and utils.show_language(language):
                #redirect to the url with the appropriate language shortcut
                return shortcuts.redirect('/%s%s' % (language, full_path))
            regex_prefix = re.compile('^/[-\w]+/')
            language_from_path = regex_prefix.findall(path)
            if language_from_path:
                language_from_path = language_from_path[0].replace('/','')
                if not referer or regex_ref.match(referer) is None:
                    if language_from_path in language_shortcuts and language_from_path!=language:
                        translation.activate(language_from_path)
                        request.LANGUAGE_CODE = translation.get_language()
                        language = translation.get_language()
                if language_from_path in language_shortcuts and language_from_path!=language:
                    #cut of the language shortcut
                    path = path.replace('/%s' % language_from_path, '', 1)
                    full_path = full_path.replace('/%s' % language_from_path, '', 1)
                    #check if the path is_included_path
                    if utils.is_included_path(path):
                        #redirect to the url with the appropriate language shortcut
                        if utils.show_language(language):
                            return shortcuts.redirect('/%s%s' % (language, full_path))
                        else:
                            return shortcuts.redirect('%s' % full_path)
                elif language_from_path==language and utils.show_language(language):
                    path = path.replace('/%s' % language_from_path, '', 1)
                    full_path = full_path.replace('/%s' % language_from_path, '', 1)
                    #check if the path is_included_path
                    if utils.is_included_path(path):
                        #render the view
                        #all the other middleware's following this middleware in
                        #settings MIDDLEWARE_CLASSES still need to be
                        #processed (process_request) + all Middleware's inside
                        #of settings MIDDLEWARE_CLASSES process_view
                        #methods need to be processed as well before actually
                        #returning the view here
                        view, args, kwargs = urlresolvers.resolve(path)
                        process_request_result = utils.process_missing_requests(self, request)
                        if process_request_result is not None:
                            return process_request_result
                        process_request_view = utils.process_missing_views(self, request, view, args, kwargs)
                        if process_request_view is not None:
                            return process_request_view
                        return view(request, *args, **kwargs)

Example 48

Project: django-urli18n
Source File: middleware.py
View license
    def process_request(self, request):
        """Process the request of according to following conditions:
        
        - Only processes ``GET`` request, since others will not be displayed in the address bar anyway
        - Only processes ``GET`` request for url path's which are not provided in ``URLI18N_EXCLUDE_PATHS`` setting. If a path is provided in ``URLI18N_EXCLUDE_PATHS`` setting it will simply not transform the url (though change the language)
        - If the url query string does not include the language parameter it will build a new url from given path and query string and redirect to it 
        - If ``URLI18N_ALWAYS_SHOW_LANGUAGE`` setting is set to ``True`` (the default) it will always show the language in the query string, if  ``URLI18N_ALWAYS_SHOW_LANGUAGE`` setting is set to ``False`` it will show the language query string only for languages which are not the default language (set via the django setting for ``LANGUAGE_CODE``)
        - If user is not navigating on the page but coming from a source which is not the domain of this project it will change the language directly when provided in the url or if not provided use the current activated language (given by process_request of django.middleware.locale.LocaleMiddleware)
        
        Args:
            - ``request``: the django request object to process
            
        Returns:
            - Either a redirect response to the right path with leading language shortcut or the view response for the view attached to the url of the path
        """
        path = request.path_info
        if request.method == 'GET' and utils.is_included_path(path):
            full_path = request.get_full_path()
            querystring_name = app_settings.URLI18N_QUERYSTRING_NAME
            
            path_parts, querystring_parts, language_querystring, language_querystring_position = utils.break_full_path(full_path)
            
            language = translation.get_language()
            host = request.get_host()
            redirect_to = None
            regex_ref = re.compile('^http[s]?://%s' % host, re.UNICODE)
            referer = request.META.get('HTTP_REFERER', None)
            language_shortcuts = [lang[0] for lang in settings.LANGUAGES]
            
            if not referer or regex_ref.match(referer) is None and language_querystring:
                #change the language according to the path if
                #its provided in the path, else try to use the
                #last activated language
                language_from_querystring = language_querystring.replace('%s=' % querystring_name,'')
                if language_from_querystring in language_shortcuts:
                    translation.activate(language_from_querystring)
                    request.LANGUAGE_CODE = translation.get_language()
                    language = translation.get_language()
            
            #reconstruct the language_querystring
            language_querystring = '%s=%s' % (querystring_name, language)
            
            if app_settings.URLI18N_ALWAYS_SHOW_LANGUAGE is False\
            and settings.LANGUAGE_CODE == language:
                #dont' rewrite urls for the default language if setting is set
                if language_querystring_position is not None:
                    querystring_parts.pop(language_querystring_position)
                    full_path = utils.reconstruct_full_path(path_parts[0], querystring_parts)
                if full_path != request.get_full_path():
                    return shortcuts.redirect(full_path)
            else:
                if language_querystring_position is not None\
                and language_querystring != querystring_parts[language_querystring_position]:
                    querystring_parts[language_querystring_position] = language_querystring
                    redirect_to = utils.reconstruct_full_path(path_parts[0], querystring_parts)
                elif language_querystring_position is None:
                    querystring_parts.append(language_querystring)
                    redirect_to = utils.reconstruct_full_path(path_parts[0], querystring_parts)
                if redirect_to is not None:
                    return shortcuts.redirect(redirect_to)

Example 49

Project: pootle
Source File: decorators.py
View license
def get_path_obj(func):
    @wraps(func)
    def wrapped(request, *args, **kwargs):
        if request.is_ajax():
            pootle_path = request.GET.get('path', None)
            if pootle_path is None:
                raise Http400(_('Arguments missing.'))

            language_code, project_code, dir_path, filename = \
                split_pootle_path(pootle_path)
            kwargs['dir_path'] = dir_path
            kwargs['filename'] = filename

            # Remove potentially present but unwanted args
            try:
                del kwargs['language_code']
                del kwargs['project_code']
            except KeyError:
                pass
        else:
            language_code = kwargs.pop('language_code', None)
            project_code = kwargs.pop('project_code', None)

        if language_code and project_code:
            try:
                path_obj = TranslationProject.objects.get_for_user(
                    user=request.user,
                    language_code=language_code,
                    project_code=project_code,
                )
            except TranslationProject.DoesNotExist:
                path_obj = None

            if path_obj is None:
                if not request.is_ajax():
                    # Explicit selection via the UI: redirect either to
                    # ``/language_code/`` or ``/projects/project_code/``
                    user_choice = request.COOKIES.get('user-choice', None)
                    if user_choice and user_choice in ('language', 'project',):
                        url = {
                            'language': reverse('pootle-language-browse',
                                                args=[language_code]),
                            'project': reverse('pootle-project-browse',
                                               args=[project_code, '', '']),
                        }
                        response = redirect(url[user_choice])
                        response.delete_cookie('user-choice')

                        return response

                raise Http404
        elif language_code:
            user_projects = Project.accessible_by_user(request.user)
            language = get_object_or_404(Language, code=language_code)
            children = language.children \
                               .filter(project__code__in=user_projects)
            language.set_children(children)
            path_obj = language
        elif project_code:
            try:
                path_obj = Project.objects.get_for_user(project_code,
                                                        request.user)
            except Project.DoesNotExist:
                raise Http404
        else:  # No arguments: all user-accessible projects
            user_projects = Project.objects.for_user(request.user)
            path_obj = ProjectSet(user_projects)

        request.ctx_obj = path_obj
        request.ctx_path = path_obj.pootle_path
        request.resource_obj = path_obj
        request.pootle_path = path_obj.pootle_path

        return func(request, path_obj, *args, **kwargs)

    return wrapped

Example 50

Project: PyScada
Source File: views.py
View license
@requires_csrf_token
def view(request,link_title):
	if not request.user.is_authenticated():
		return redirect('/accounts/login/?next=%s' % request.path)

	page_template = loader.get_template('content_page.html')
	widget_row_template = loader.get_template('widget_row.html')

	try:
		view = View.objects.get(link_title=link_title)
	except:
		return HttpResponse(status=404)

	page_list = view.pages.filter(groupdisplaypermission__hmi_group__in=request.user.groups.iterator).distinct()

	sliding_panel_list = view.sliding_panel_menus.filter(groupdisplaypermission__hmi_group__in=request.user.groups.iterator).distinct()

	visible_widget_list = Widget.objects.filter(groupdisplaypermission__hmi_group__in=request.user.groups.iterator,page__in=page_list.iterator).values_list('pk',flat=True)
	visible_custom_html_panel_list = CustomHTMLPanel.objects.filter(groupdisplaypermission__hmi_group__in=request.user.groups.iterator).values_list('pk',flat=True)
	visible_chart_list = Chart.objects.filter(groupdisplaypermission__hmi_group__in=request.user.groups.iterator).values_list('pk',flat=True)

	visible_control_element_list = GroupDisplayPermission.objects.filter(hmi_group__in=request.user.groups.iterator).values_list('control_items',flat=True)

	panel_list   = sliding_panel_list.filter(position__in=(1,2,))
	control_list = sliding_panel_list.filter(position=0)

	current_row = 0
	has_chart = False
	widgets = []
	widget_rows_html = ""
	pages_html = ""
	for page in view.pages.filter(groupdisplaypermission__hmi_group__in=request.user.groups.iterator).distinct():
		current_row = 0
		has_chart = False
		widgets = []
		widget_rows_html = ""
		for widget in page.widget_set.all():
			# check if row has changed
			if current_row <> widget.row:
				# render new widget row and reset all loop variables
				widget_rows_html += widget_row_template.render(RequestContext(request,{'row':current_row,'has_chart':has_chart,'widgets':widgets,'visible_control_element_list':visible_control_element_list}))
				current_row = widget.row
				has_chart = False
				widgets = []
			if not widget.pk in visible_widget_list:
				continue
			if not widget.visable:
				continue
			if widget.chart:
				if not widget.chart.visable():
					continue
				if not widget.chart.pk in visible_chart_list:
					continue
				has_chart = True
				widgets.append(widget)
			elif widget.control_panel:
				widgets.append(widget)
			elif widget.process_flow_diagram:
				widgets.append(widget)
			elif widget.custom_html_panel:
				if not widget.custom_html_panel.pk in visible_custom_html_panel_list:
					continue
				widgets.append(widget)
		widget_rows_html += widget_row_template.render(RequestContext(request,{'row':current_row,'has_chart':has_chart,'widgets':widgets,'visible_control_element_list':visible_control_element_list}))
		pages_html += page_template.render(RequestContext(request,{'page':page,'widget_rows_html':widget_rows_html}))

	c = {
		'page_list': page_list,
		'pages_html':pages_html,
		'panel_list': panel_list,
		'control_list':control_list,
		'user': request.user,
		'visible_control_element_list':visible_control_element_list,
		'view_title':view.title,
		'version_string':core_version
	}

	log.webnotice('open hmi',request.user)
	return TemplateResponse(request, 'view.html', c)