django.shortcuts.render_to_response

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

200 Examples 7

Example 151

Project: django-calendar
Source File: events.py
View license
@login_required
def edit(request, event_slug, cal_type="5", template_name=None, next=None):
    """ edit a withcal """
    (event, err) = fetch_from_url(request, event_slug)
    if err:
        return err
    request_user = request.user
    if request.method == 'POST':
        f = BaseEventForm(request.POST)
        if f.is_valid():
            event.start = f.cleaned_data['start_time']
            event.end = f.cleaned_data['end_time']
            event.allDay = f.cleaned_data['check_whole_day']
            event.category = f.cleaned_data['category']
            event.priority = f.cleaned_data['priority']
            event.end_recurring_period = f.cleaned_data['end_recurring_period']
            recursion_frequency = f.cleaned_data['recursion_frequency']
            recursion_count = f.cleaned_data['recursion_count']
            recursion_byweekday = f.cleaned_data['recursion_byweekday']
            recursion_bymonthday = f.cleaned_data['recursion_bymonthday']

            #first we have to check if the current event is recurring, if so we:
            #the recursion parameters are required
            if f.cleaned_data['add_recursion']:
                recursion_params = recursion_count + recursion_byweekday + recursion_bymonthday
                if event.recursion is None:
                    recursion = Recursion(frequency=recursion_frequency, params=recursion_params)
                    recursion.save()
                    event.recursion = recursion
                else :
                    recursion = event.recursion
                    recursion.frequency = recursion_frequency
                    recursion.params = recursion_params
                    recursion.save()
            else :
                if event.recursion is not None:
                    recursion = event.recursion
                    event.recursion = None
                    event.save()
                    recursion.delete()

            event.save()
            #notify all concerned users by the object by the new comment
            #users_tonotify = ToNotify.objects.filter(event=event).exclude(user=request_user)
            #for user_tonotify in users_tonotify:
                #user = user_tonotify.user
                #notification.send([user], "cal_updated", {'event': event, 'user':request_user,})

            if not request.is_ajax():
                return HttpResponseRedirect(reverse(next, args=(event.get_url(),)))
            response = ({'success':'True'})
        else:
            response = errors_as_json(f)
        if request.is_ajax():
            json = simplejson.dumps(response, ensure_ascii=False)
            return HttpResponse(json, mimetype="application/json")
    else:

        if event.recursion:
            params = event.recursion.get_params()
            count = ''
            byweekday = ''
            bymonthday = ''
            if 'count' in params:
                count = params['count']
            if 'byweekday' in params:
                try:
                    byweekday = [int(params['byweekday'])]
                except:
                    byweekday = params['byweekday']
            if 'bymonthday' in params:
                try:
                    bymonthday = [int(params['bymonthday'])]
                except:
                    bymonthday = params['bymonthday']
            f = BaseEventForm({'start_date': event.start.date(),
                      'start_time': event.start.time().strftime("%I:%M %p"),
                      'end_date': event.end.date(),
                      'end_time': event.end.time().strftime("%I:%M %p"),
                      'category': event.cal_category,
                      'priority': event.priority,
                      'check_whole_day': event.allDay,
                      'end_recurring_period': event.end_recurring_period,
                      'recursion_frequency' : event.recursion.frequency,
                      'add_recursion': True,
                      'recursion_count': count,
                      'recursion_byweekday':byweekday,
                      'recursion_bymonthday':bymonthday,
                      })
        else :
            f = BaseEventForm({'start_date': event.start.date(),
                      'start_time': event.start.time().strftime("%I:%M %p"),
                      'end_date': event.end.date(),
                      'end_time': event.end.time().strftime("%I:%M %p"),
                      'check_whole_day': event.allDay,
                      'category': event.category,
                      'priority': event.priority,
                      'end_recurring_period': event.end_recurring_period,
                      })
    c = RequestContext(request, {'form': f,
                                 'action': event.get_edit_url(),
                                 'event': event,
                                 })

    return render_to_response(template_name, c)

Example 152

Project: Observatory
Source File: projects.py
View license
@login_required
def add(request):
  feed_repo_form = FeedRepositoryForm()
  cloned_repo_form = ClonedRepositoryForm()
  project_form = ProjectForm()
  blog_form = BlogForm()
  
  form_keys = {
    1: ('title', 'description', 'website', 'wiki'),
    2: ('web_url', 'clone_url', 'vcs', 'repo_rss', 'cmd'),
    3: ('url', 'rss')
  }
  
  if 'current' in request.POST:
    current = int(request.POST['current'])
  else:
    current = 0
  
  if current == 1:
    project_form = ProjectForm(request.POST)
    if not project_form.is_valid():
      current -= 1
  
  elif current == 2:
    if 'clone_url' in request.POST:
      cloned_repo_form = ClonedRepositoryForm(request.POST)
      if not cloned_repo_form.is_valid():
        current -= 1
    elif 'repo_rss' in request.POST:
      feed_repo_form = FeedRepositoryForm(request.POST)
      if not feed_repo_form.is_valid():
        current -= 1
  
  elif current == 3:
    blog_form = BlogForm(request.POST)
    if not ('url' not in request.POST or blog_form.is_valid()):
      current -= 1
  
  # go to the next form
  current += 1
  
  # if there are more parts to the form
  if current < 4:
    # remove the csrf token and current from a copy of the POST data
    post = request.POST.copy()
    if 'csrfmiddlewaretoken' in post:
      post.pop('csrfmiddlewaretoken')
      post.pop('current')

      # remove any of the keys that should be set on this form page
      for key in form_keys[current]:
        try:
          post.pop(key)
        except:
          pass
    
    return render_to_response('projects/add.html', {
        'parts': [1, 2, 3],
        'current': current,
        'previous_data': post,
        'cloned_repo_form': cloned_repo_form,
        'feed_repo_form': feed_repo_form,
        'project_form': project_form,
        'blog_form': blog_form,
        'js_page_id': 'add_project'
      }, context_instance = RequestContext(request))
  
  # otherwise, if the form is complete, create the project
  else:
    # validate and clean all forms
    project_form = ProjectForm(request.POST)
    cloned_repo_form = ClonedRepositoryForm(request.POST)
    feed_repo_form = FeedRepositoryForm(request.POST)
    blog_form = BlogForm(request.POST)
    
    for form in [project_form, cloned_repo_form, feed_repo_form, blog_form]:
      form.is_valid()
    
    # create the blog object
    if 'rss' in request.POST:
      blog = Blog(url = blog_form.cleaned_data['url'],
                  rss = blog_form.cleaned_data['rss'],
                  from_feed = True)
    else:
      blog = Blog(from_feed = False)
    blog.save()

    # create the repository object
    # if using google code removes read only addition
    # if [email protected] is mistakenly typed, git:// is placed in
    if 'clone_url' in request.POST:
      url = cloned_repo_form.cleaned_data['clone_url']
      gitfix = url.replace('[email protected]', 'git://')
      url = gitfix
      if "google.com" in url:
        split = url.split(' ')
        url = split[0]

      repo = Repository(web_url = cloned_repo_form.cleaned_data['web_url'],
                        clone_url = url,
                        from_feed = False)
    else:
      repo = Repository(web_url = feed_repo_form.cleaned_data['web_url'],
                        repo_rss = feed_repo_form.cleaned_data['repo_rss'],
                        from_feed = True)
    repo.save()

    # create the project object
    project = Project(title = project_form.cleaned_data['title'],
                      website = project_form.cleaned_data['website'],
                      wiki = project_form.cleaned_data['wiki'],
                      description = project_form.cleaned_data['description'],
                      active = True,
                      repository_id = repo.id,
                      blog_id = blog.id,
					  pending = True)

    # get the project a primary key
    project.save()

    # associate the current user with the project as an author
    project.authors.add(request.user)

    # save the project again
    project.save()

    # Set the active flag as true
    project.active = True

    # Save the project again
    project.save()

    # redirect to the show page for the new project
    return HttpResponseRedirect(reverse(show, args = (project.url_path,)))

Example 153

Project: django-inviting
Source File: views.py
View license
def register(request,
             invitation_key,
             wrong_key_template='invitation/wrong_invitation_key.html',
             redirect_to_if_authenticated='/',
             success_url=None,
             form_class=RegistrationFormInvitation,
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register via invitation.

    Send invitation email and then redirect to success URL if the
    invitation form is valid. Redirect named URL ``invitation_unavailable``
    on InvitationError. Render invitation form template otherwise. Sends
    registration.signals.user_registered after creating the user.

    **Required arguments:**

    :invitation_key:
        An invitation key in the form of ``[\da-e]{40}``

    **Optional arguments:**

    :wrong_key_template:
        Template to be used when an invalid invitation key is supplied.
        Default value is ``invitation/wrong_invitation_key.html``.

    :redirect_to_if_authenticated:
        URL to be redirected when an authenticated user calls this view.
        Defaults value is ``/``

    :success_url:
        The URL to redirect to on successful registration. Default value is
        ``None``, ``invitation_registered`` will be resolved in this case.

    :form_class:
        A form class to use for registration. Takes the invited email as first
        argument to its constructor.

    :template_name:
        A custom template to use. Default value is
        ``registration/registration_form.html``.

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

    **Templates:**

    ``invitation/invitation_form.html`` or ``template_name`` keyword
    argument as the *main template*.

    ``invitation/wrong_invitation_key.html`` or ``wrong_key_template`` keyword
    argument as the *wrong key template*.

    **Context:**

    ``RequestContext`` instances are used rendering both templates. Context,
    in addition to ``extra_context``, contains:

    For wrong key template
        :invitation_key: supplied invitation key

    For main template
        :form:
            The registration form.
    """
    if request.user.is_authenticated():
        return HttpResponseRedirect(redirect_to_if_authenticated)
    try:
        invitation = Invitation.objects.find(invitation_key)
    except Invitation.DoesNotExist:
        context = apply_extra_context(RequestContext(request), extra_context)
        return render_to_response(wrong_key_template,
                                  {'invitation_key': invitation_key},
                                  context_instance=context)
    if request.method == 'POST':
        form = form_class(invitation.email, request.POST, request.FILES)
        if form.is_valid():
            new_user = form.save()
            invitation.mark_accepted(new_user)
            user_registered.send(sender="invitation",
                                 user=new_user,
                                 request=request)
            return HttpResponseRedirect(success_url or \
                                             reverse('invitation_registered'))
    else:
        form = form_class(invitation.email)
    context = apply_extra_context(RequestContext(request), extra_context)
    return render_to_response(template_name,
                              {'form': form},
                              context_instance=context)

Example 154

Project: django-compositepks
Source File: comments.py
View license
def post_comment(request, next=None):
    """
    Post a comment.

    HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
    errors a preview template, ``comments/preview.html``, will be rendered.
    """
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest("Missing content_type or object_pk field.")
    try:
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.get(pk=object_pk)
    except TypeError:
        return CommentPostBadRequest(
            "Invalid content_type value: %r" % escape(ctype))
    except AttributeError:
        return CommentPostBadRequest(
            "The given content-type %r does not resolve to a valid model." % \
                escape(ctype))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type %r and object PK %r exists." % \
                (escape(ctype), escape(object_pk)))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Construct the comment form
    form = comments.get_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: %s" % \
                escape(str(form.security_errors())))

    # If there are errors or if we requested a preview show the comment
    if form.errors or preview:
        template_list = [
            "comments/%s_%s_preview.html" % tuple(str(model._meta).split(".")),
            "comments/%s_preview.html" % model._meta.app_label,
            "comments/preview.html",
        ]
        return render_to_response(
            template_list, {
                "comment" : form.data.get("comment", ""),
                "form" : form,
            },
            RequestContext(request, {})
        )

    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )

    for (receiver, response) in responses:
        if response == False:
            return CommentPostBadRequest(
                "comment_will_be_posted receiver %r killed the comment" % receiver.__name__)

    # Save the comment and signal that it was saved
    comment.save()
    signals.comment_was_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )

    return next_redirect(data, next, comment_done, c=comment._get_pk_val())

Example 155

Project: pyfreebilling
Source File: views.py
View license
@staff_member_required
def global_stats_view(request, vue):
    # set start_date and end_date
    # default yesterday stats
    if vue == 'customer' or vue == 'dest_customer':
        qs = DimCustomerDestination.objects.all()
    if vue == 'provider' or vue == 'dest_provider':
        qs = DimProviderDestination.objects.all()

    current_tz = pytz.utc
    dt = datetime.datetime.now()
    end_date = datetime.date(dt.year, dt.month, dt.day)
    # end_date = datetime.date(2014, 8, 28)
    start_date = end_date - datetime.timedelta(days=1)
    qs_orderby = '-total_sell'

    # Get the q GET parameter
    # date from and to and check value
    start_d = {'y': [], 'm': [], 'd': [], 'status': True}
    end_d = {'y': [], 'm': [], 'min': [], 'status': True}
    li = ['y', 'm', 'd']
    for i in li:
        start_d[str(i)] = request.GET.get("from_" + str(i))
        if start_d[str(i)] and start_d[str(i)].isnumeric():
            start_d[str(i)] = int(start_d[str(i)])
        else:
            start_d['status'] = False
        end_d[str(i)] = request.GET.get("to_" + str(i))
        if end_d[str(i)] and end_d[str(i)].isnumeric():
            end_d[str(i)] = int(end_d[str(i)])
        else:
            end_d['status'] = False
    # dest num
    dest_num = request.GET.get("dest_num")
    company = request.GET.get("company")
    if start_d['status']:
        start_date = datetime.datetime(
            start_d['y'], start_d['m'], start_d['d'], 00, 00)
    if end_d['status']:
        end_date = datetime.datetime(
            end_d['y'], end_d['m'], end_d['d'], 00, 00)
    if start_date and end_date:
        qs = qs.filter(date__date__range=(start_date, end_date))

    if dest_num:
        qs = qs.filter(destination__startswith=dest_num)

    if company:
        if vue == 'customer' or vue == 'dest_customer':
            qs = qs.filter(customer__name__contains=company)
        if vue == 'provider' or vue == 'dest_provider':
            qs = qs.filter(provider__name__contains=company)

    if vue == 'customer':
        qs1 = qs.values('customer__name', 'customer__cb_currency__code')
    if vue == 'dest_customer' or vue == 'dest_provider':
        qs1 = qs.values('destination')
    if vue == 'provider':
        qs1 = qs.values('provider__name', 'provider__cb_currency__code')
    stats_table = qs1.\
        annotate(total_sell=Sum('total_sell')).\
        annotate(success_calls=Sum('success_calls')).\
        annotate(total_calls=Sum('total_calls')).\
        annotate(total_cost=Sum('total_cost')).\
        annotate(total_duration=Sum('total_duration')).\
        annotate(max_duration=Max('max_duration')).\
        annotate(min_duration=Min('min_duration')).\
        annotate(avg_duration=Min('avg_duration')).\
        order_by('-total_sell')
    total_table = qs.\
        aggregate(total_sell=Sum('total_sell'),
            success_calls=Sum('success_calls'),\
            total_calls=Sum('total_calls'),\
            total_cost=Sum('total_cost'),\
            total_duration=Sum('total_duration'),\
            max_duration=Max('max_duration'),\
            min_duration=Min('min_duration'),\
            avg_duration=Min('avg_duration'))

    if vue == 'customer':
        table = TopCustTable(stats_table)
    if vue == 'dest_customer':
        table = TopDestCustTable(stats_table)
    if vue == 'provider':
        table = TopProvTable(stats_table)
    if vue == 'dest_provider':
        table = TopDestProvTable(stats_table)
    RequestConfig(request, paginate={"per_page": 100}).configure(table)
    #import pdb; pdb.set_trace()
    return render_to_response('admin/customers_stats.html', locals(),
                              context_instance=RequestContext(request))

Example 156

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

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

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

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

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

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

    target_language = Language.objects.by_code_or_alias_or_404(lang_code)

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

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

    translated_strings = Translation.objects.filter(
        resource__in=resources,
        language=target_language,
        source_entity__pluralized=False,
        rule=5).count()

    reviewed_strings = Translation.objects.filter(
        resource__in=resources,
        language=target_language,
        source_entity__pluralized=False,
        rule=5,
        reviewed=True).count()

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

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

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

    lotte_init.send(None, request=request, resources=resources,
        language=target_language)

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

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

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

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

Example 157

Project: pombola
Source File: views.py
View license
def position(request, pt_slug, ok_slug=None, o_slug=None):
    new_url = get_position_type_redirect(pt_slug, ok_slug, o_slug)
    if new_url:
        return redirect(new_url)

    title = get_object_or_404(
        models.PositionTitle,
        slug=pt_slug
    )

    # If this position title is one associated with any parliamentary
    # session, show alternative parliamentary sessions:
    possible_sessions = []
    if models.ParliamentarySession.objects.filter(
            position_title=title
    ).exists():
        possible_sessions = models.ParliamentarySession.objects.order_by('name')

    page_title = title.name
    if o_slug:
        organisation = get_object_or_404(models.Organisation,
                                         slug=o_slug)
        page_title += " of " + organisation.name
    elif ok_slug:
        organisation_kind = get_object_or_404(models.OrganisationKind,
                                              slug=ok_slug)
        page_title += " of any " + organisation_kind.name

    session = None
    session_slug = request.GET.get('session')
    if session_slug:
        session = get_object_or_404(
            models.ParliamentarySession,
            slug=session_slug
        )
    # Build up context data for the links to switch between particular
    # parliamentary sessions and all current position holders:
    session_details = []
    for s in [None] + list(possible_sessions):
        if session != s:
            params = request.GET.copy()
            if s is None:
                session_filter = 'Current'
                params.pop('session', None)
                override = override_current_session(session)
                if override is None:
                    path = request.path
                else:
                    path = override.positions_url()
            else:
                session_filter = s.name
                params['session'] = s.slug
                path = s.positions_url()
            session_details.append({
                'url': path + '?' + params.urlencode(),
                'name': session_filter,
                'session': s,
                'should_link': session != s,
            })

    # If a particular parliamentary session has been requested, only
    # return positions that overlap with the period of that
    # session. Otherwise only return currently active positions.
    if session:
        positions = title.position_set.overlapping_dates(
            session.start_date, session.end_date
        )
    else:
        positions = title.position_set.all().currently_active()
    if ok_slug is not None:
        positions = positions.filter(organisation__kind__slug=ok_slug)
    if o_slug is not None:
        positions = positions.filter(organisation__slug=o_slug)

    # Order by place name unless ordering by person name is requested:
    order = 'place'
    if request.GET.get('order') == 'name':
        order = 'person__sort_name'
    positions = positions.order_by(order)

    positions = positions.select_related('person',
                                         'organisation',
                                         'title',
                                         'place',
                                         'place__kind',
                                         'place__parent_place')

    place_slug = request.GET.get('place_slug')
    if place_slug:
        positions = positions.filter(
            Q(place__slug=place_slug) | Q(place__parent_place__slug=place_slug)
        )

    # see if we should show the grid
    view = request.GET.get('view', 'list')

    if view == 'grid':
        template = 'core/position_detail_grid.html'
        places   = [] # not relevant to this view
    else:
        template = 'core/position_detail.html'

        # Collect all the places those positions refer to:
        child_places = sorted(set(x.place for x in positions if x.place),
                              key=lambda p: p.name)

        # Extract the parents of those places as well:
        parent_place_ids = [x.parent_place.id for x in child_places if (x and x.parent_place)]
        parent_places = models.Place.objects.filter(id__in=parent_place_ids).select_related('kind')

        # combine the places into a single list for the search drop down
        places = []
        places.extend(parent_places)
        places.extend(child_places)

    return render_to_response(
        template,
        {
            'object':     title,
            'page_title': page_title,
            'positions':  positions,
            'order':      request.GET.get('order'),
            'places':     places,
            'place_slug': place_slug,
            'session': session,
            'session_details': session_details,
        },
        context_instance=RequestContext(request)
    )

Example 158

Project: django-leonardo
Source File: models.py
View license
    def process(self, request, **kw):
        page_url = self.parent.get_absolute_url()

        if "path_mapper" in self.app_config:
            path_mapper = get_object(self.app_config["path_mapper"])
            path, page_url = path_mapper(
                request.path,
                page_url,
                appcontent_parameters=self.parameters
            )
        else:
            path = request._feincms_extra_context['extra_path']

        # Resolve the module holding the application urls.
        urlconf_path = self.app_config.get('urls', self.urlconf_path)

        try:
            fn, args, kwargs = resolve(path, urlconf_path)
        except (ValueError, Resolver404):
            raise Resolver404(str('Not found (resolving %r in %r failed)') % (
                path, urlconf_path))

        # Variables from the ApplicationContent parameters are added to request
        # so we can expose them to our templates via the appcontent_parameters
        # context_processor
        request._feincms_extra_context.update(self.parameters)
        request._feincms_extra_context.update({'widget': self})

        # Save the application configuration for reuse elsewhere
        request._feincms_extra_context.update({
            'app_config': dict(
                self.app_config,
                urlconf_path=self.urlconf_path,
            ),
        })

        view_wrapper = self.app_config.get("view_wrapper", None)
        if view_wrapper:
            fn = partial(
                get_object(view_wrapper),
                view=fn,
                appcontent_parameters=self.parameters
            )

        output = fn(request, *args, **kwargs)

        # handle django rest framework as external application
        if hasattr(output, 'renderer_context'):
            output.context_data = output.renderer_context
            output.standalone = True

        if isinstance(output, HttpResponse):

            # update context
            if hasattr(output, 'context_data'):
                output.context_data['widget'] = self
            else:
                output.context_data = {'widget': self}

            if self.send_directly(request, output):
                return output
            elif output.status_code == 200:

                if self.unpack(request, output) and 'view' in kw:
                    # Handling of @unpack and UnpackTemplateResponse
                    kw['view'].template_name = output.template_name
                    kw['view'].request._feincms_extra_context.update(
                        output.context_data)

                else:
                    # If the response supports deferred rendering, render the
                    # response right now. We do not handle template response
                    # middleware.
                    if hasattr(output, 'render') and callable(output.render):
                        output.render()

                    self.rendered_result = mark_safe(
                        output.content.decode('utf-8'))

                self.rendered_headers = {}

                # Copy relevant headers for later perusal
                for h in ('Cache-Control', 'Last-Modified', 'Expires'):
                    if h in output:
                        self.rendered_headers.setdefault(
                            h, []).append(output[h])

        elif isinstance(output, tuple) and 'view' in kw:
            kw['view'].template_name = output[0]
            kw['view'].request._feincms_extra_context.update(output[1])
            # our hack
            # no template and view change and save content for our widget
            context = output[1]
            context['widget'] = self
            self.rendered_result = render_to_string(
                output[0], RequestContext(request, context))
        else:
            self.rendered_result = mark_safe(output)

        # here is the magic !
        # return renderered parent template !
        context = RequestContext(request, {})
        return render_to_response(
            self.parent.theme.template,
            context
        )

Example 159

Project: theyworkforyou
Source File: views.py
View license
def guardian_candidate(request, aristotle_id=None, raw_name=None, raw_const_name=None):    
    constituency_name = raw_const_name or ""
    constituency_aristotle_id = 0
    candidate_name = ""
    found_name = "Not found"
    candidacy = False
    candidate = False
    candidate_id_mapping = False
    error_message = ""
    debug_message = ""
    url_for_seat = ""
    # note these Guardian labels are not quite the same as the TWFY verb defaults
    # And these are set up to start with agreement (hence descending value order)
    result_labels = (
        (100, "Strongly<br/>agree"),
        (75, "Agree<br/>&nbsp;"),
        (50, "Neither&nbsp;agree<br/>nor&nbsp;disagree"),
        (25, "Disagree<br/>&nbsp;"),
        (0, "Strongly<br/>disagree")
        )
    if aristotle_id:
        try:
            aristotle_id = int(aristotle_id)
            candidate_id_mapping = db.Query(AristotleToYnmpCandidateMap).filter("aristotle_id =", aristotle_id).get()
        except exceptions.ValueError:
            aristotle_id = None
            error_message = "Badly formed aristotle_id" # unexpected: urls.py prevents non-digits
        if candidate_id_mapping:
            debug_message = debug_message + (" [map-hit: %s] " % candidate_id_mapping.ynmp_id)
            if candidate_id_mapping.ynmp_id == 0: # explicit block: *never* matches
                error_message = "Map: blocked"
            else:
                candidate = db.Query(Candidate).filter("ynmp_id =", candidate_id_mapping.ynmp_id).get()
        if not candidate and not error_message:
            url = "http://www.guardian.co.uk/politics/api/person/%s/json" % aristotle_id;
            result = urlfetch.fetch(url)
            if result.status_code == 200:
                candidateData = json.loads( result.content )
                if candidateData['person']:
                    candidate_name = candidateData['person']['name']
                if candidate_name == "":
                    error_message = "No name found from Aristotle"
                else:
                    jsonCandidacies = candidateData['person']['candidacies']
                    for c in jsonCandidacies:
                        if c['election'] and c['election']['year'] == "2010":
                            constituency_aristotle_id = c['constituency']['aristotle-id']
                            constituency_name = c['constituency']['name']
                            break
                    if constituency_name == "": # Guardian doesn't believe this is a candidate: don't show
                        error_message = "No 2010 constituency found from Aristotle"
            else:
                error_message = "Aristotle JSON load failed with HTTP status %s" % result.status_code
    elif raw_name:
        candidate_name = raw_name
    if not error_message:
        if not candidate:
            candidate_code = re.sub('\W+', "_", candidate_name.lower())
            debug_message =  debug_message + " [candidate_code=" + candidate_code + "] "
            candidate = db.Query(Candidate).filter("code =", candidate_code).get()
        if candidate:
            if aristotle_id and candidate.ynmp_id and not candidate_id_mapping: # we've discovered a new mapping: save it
                candidate_id_mapping = AristotleToYnmpCandidateMap()
                candidate_id_mapping.aristotle_id = aristotle_id
                candidate_id_mapping.ynmp_id = candidate.ynmp_id
                candidate_id_mapping.put()
                debug_message=debug_message + (" [map-saved %s] " % candidate.ynmp_id)
            # note: there may be multiple candidacies, but for now we take just the one
            candidacy = db.Query(Candidacy).filter("candidate =", candidate).get()
        else:
            # We can't easily search on surname (suffix-searches v. inefficient in datastore)
            # ...unless we added it as another property.
            # so instead find this seat, and check the surnames of candidates in that seat
            # Remember this search is because the name match didn't work already, so let's try surname
            surname = candidate_code.split('_')[-1]
            if constituency_aristotle_id and False: # TODO: lookup in aristotle:ynmp-id map
                seat_ynmp_id = constituency_aristotle_id # would be mapped
                seat = db.Query(Seat).filter("ynmp_id =", seat_ynmp_id).get()
            else:
                seat_code = re.sub('\W+', "_", constituency_name.lower())
                seat = db.Query(Seat).filter("code =", seat_code).get()
            if seat:
                candidacies = db.Query(Candidacy).filter("seat =", seat)
                surname_matches = []
                for c in candidacies:
                    if c.candidate.code.split('_')[-1] == surname:
                        surname_matches.append(c)
                if len(surname_matches) == 0:
                    error_message = "%d matches on surname %s in %s" % (0, surname, seat.name)
                elif len(surname_matches) == 1:
                    candidacy = surname_matches[0]
                else: # surname clash: disambiguate by first name
                    first_name = candidate_code.split('_')[0]
                    first_name_matches = []
                    for c in surname_matches:
                        if c.candidate.code.split('_')[0] == first_name:
                            first_name_matches.append(c)
                    if len(first_name_matches) == 1:
                        candidacy = first_name_matches[0]
                    else: 
                        # TODO: really should disambigiute on full name here (may have middle initial?)
                        # TODO: or maybe compare first initials which may be unique?
                        # TODO: or party! ...but in practice it turns out this is almost never happening anyway
                        error_message = "%d matches on surname %s, %d matches on first name %s, in %s" % (len(surname_matches), surname, len(first_name_matches), first_name, seat.name)
                        candidacy = False
            else:
                error_message = "No exact name match (%s), no seat found matching (%s)" % (candidate_code, seat_code)
        if candidacy:
            found_name = candidacy.candidate.name
            url_for_seat = "http://election.theyworkforyou.com/quiz/seats/%s" % candidacy.seat.code
    # TODO: some of these strings are included in HTML comment: should check for and collapse "--"         
    if not error_message:
        error_message = "OK"
    return render_to_response('guardian_candidate.html', {
      'name_canonical': found_name, 
      'candidacy': candidacy, 
      'url_for_seat': url_for_seat,
      'result_labels': result_labels,
      'error_message': error_message,
      'debug_message': "aristotle_id=%s, raw_name=%s, raw_const_name=%s\n  %s" % (aristotle_id, raw_name, raw_const_name, debug_message)
    })

Example 160

Project: snowy
Source File: admin.py
View license
    def render_revision_form(self, request, obj, version, revision, context, template, redirect_url):
        """Renders the object revision form."""
        model = self.model
        opts = model._meta
        object_id = obj.pk
        ordered_objects = opts.get_ordered_objects()
        app_label = opts.app_label
        object_version = version.object_version
        ModelForm = self.get_form(request, obj)
        formsets = []
        if request.method == "POST":
            form = ModelForm(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
            else:
                form_validated = False
                new_object = obj
            for FormSet in self.get_formsets(request, new_object):
                formset = FormSet(request.POST, request.FILES,
                                  instance=new_object)
                formsets.append(formset)
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=True)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=True)
                change_message = _(u"Reverted to previous version, saved on %(datetime)s") % {"datetime": format(version.revision.date_created, _(settings.DATETIME_FORMAT))}
                self.log_change(request, new_object, change_message)
                self.message_user(request, _(u'The %(model)s "%(name)s" was reverted successfully. You may edit it again below.') % {"model": opts.verbose_name, "name": unicode(obj)})
                return HttpResponseRedirect(redirect_url)
        else:
            initial = deserialized_model_to_dict(object_version, revision)
            form = ModelForm(instance=obj, initial=initial)
            for FormSet in self.get_formsets(request, obj):
                formset = FormSet(instance=obj)
                try:
                    attname = FormSet.fk.attname
                except AttributeError:
                    # This is a GenericInlineFormset, or similar.
                    attname = FormSet.ct_fk_field_name
                pk_name = FormSet.model._meta.pk.name
                initial_overrides = dict([(getattr(version.object, pk_name), version) for version in revision if version.object.__class__ == FormSet.model and unicode(getattr(version.object, attname)) == unicode(object_id)])
                initial = formset.initial
                for initial_row in initial:
                    pk = initial_row[pk_name]
                    if pk in initial_overrides:
                         initial_row.update(deserialized_model_to_dict(initial_overrides[pk], revision))
                         del initial_overrides[pk]
                    else:
                       initial_row["DELETE"] = True
                initial.extend([deserialized_model_to_dict(override, revision) for override in initial_overrides.values()])
                # HACK: no way to specify initial values.
                formset._total_form_count = len(initial)
                formset.initial = initial
                formset._construct_forms()
                formsets.append(formset)
        # Generate the context.
        adminForm = admin.helpers.AdminForm(form, self.get_fieldsets(request, obj), self.prepopulated_fields)
        media = self.media + adminForm.media
        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            inline_admin_formset = admin.helpers.InlineAdminFormSet(inline, formset, fieldsets)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
        context.update({"adminform": adminForm,
                        "object_id": obj.pk,
                        "original": obj,
                        "is_popup": False,
                        "media": mark_safe(media),
                        "inline_admin_formsets": inline_admin_formsets,
                        "errors": admin.helpers.AdminErrorList(form, formsets),
                        "root_path": self.admin_site.root_path,
                        "app_label": app_label,
                        "add": False,
                        "change": True,
                        "has_add_permission": self.has_add_permission(request),
                        "has_change_permission": self.has_change_permission(request, obj),
                        "has_delete_permission": self.has_delete_permission(request, obj),
                        "has_file_field": True, # FIXME - this should check if form or formsets have a FileField,
                        "has_absolute_url": hasattr(self.model, "get_absolute_url"),
                        "ordered_objects": ordered_objects,
                        "form_url": mark_safe(request.path),
                        "opts": opts,
                        "content_type_id": ContentType.objects.get_for_model(self.model).id,
                        "save_as": self.save_as,
                        "save_on_top": self.save_on_top,
                        "root_path": self.admin_site.root_path,})
        return render_to_response(template, context, RequestContext(request))

Example 161

Project: ndgrutedb
Source File: buildgraph.py
View license
def buildGraph(request):

  error_msg = ""

  if request.method == "POST":
    form = BuildGraphForm(request.POST, request.FILES) # instantiating form
    if form.is_valid():

      # Acquire proj names
      proj_dir = form.cleaned_data["UserDefprojectName"]
      site = form.cleaned_data["site"]
      subject = form.cleaned_data["subject"]
      session = form.cleaned_data["session"]
      scanId = form.cleaned_data["scanId"]

      """
      # Private project error checking
      if (form.cleaned_data["Project_Type"] == "private"):
        if not request.user.is_authenticated():
          error_msg = "You must be logged in to make/alter a private project! \
              Please Login or make/alter a public project."

        # Untested TODO: Add join to ensure it a private project
        elif BuildGraphModel.objects.filter(owner=request.user, \
            project_name=proj_dir, site=site, subject=subject, \
            session=session, scanId=scanId).exists():

           error_msg = "The scanID you requested to create already \
               exists in this project path. Please change any of the form values."
      """
      if error_msg:
        return render_to_response(
          "buildgraph.html",
          {"buildGraphform": form, "error_msg": error_msg},
          context_instance=RequestContext(request)
          )

      """
      # If a user is logged in associate the project with thier directory
      if form.cleaned_data["Project_Type"] == "private":
        proj_dir = os.path.join(request.user.username, proj_dir)
      else:
      """
      proj_dir = os.path.join("public", proj_dir)

      # Adapt project name if necesary on disk
      proj_dir = adaptProjNameIfReq(os.path.join(
          settings.MEDIA_ROOT, proj_dir)) # Fully qualify AND handle identical projects

      usrDefProjDir = os.path.join(proj_dir, site, subject, session, scanId)
      """ Define data directory paths """
      derivatives, graphs = defDataDirs(usrDefProjDir)

      # Create a model object to save data to DB

      grModObj = BuildGraphModel(project_name = form.cleaned_data["UserDefprojectName"])
      grModObj.location = usrDefProjDir # The particular scan location

      grModObj.site = site
      grModObj.subject = subject
      grModObj.session = session
      grModObj.scanId = scanId

      if request.user.is_authenticated():
        grModObj.owner = request.user # Who created the project

      invariants = form.cleaned_data["invariants"]
      graph_size = form.cleaned_data["graph_size"]
      email = form.cleaned_data["email"]

      if graph_size == "big" and not email:
        return render_to_response(
          "buildgraph.html",
          {"buildGraphform": form, "error_msg": "Email address must be \
              provided when processing big graphs due to http timeout's possibly occurring."},
          context_instance=RequestContext(request)
          )

      """ Acquire fileNames """
      fiber_fn = form.cleaned_data["fiber_file"].name # get the name of the file input by user
      if form.cleaned_data["data_atlas_file"]:
        data_atlas_fn = form.cleaned_data["data_atlas_file"].name
        print "Storing data atlas ..."
        saveFileToDisk(form.cleaned_data["data_atlas_file"], 
            os.path.join(derivatives, data_atlas_fn))

      print "Storing fibers ..."
      """ Save files in appropriate location """
      saveFileToDisk(form.cleaned_data["fiber_file"], 
          os.path.join(derivatives, fiber_fn))
      grModObj.save() # Save project data to DB after file upload

      # add entry to owned project
      if request.user.is_authenticated():
        ownedProjModObj = OwnedProjects(project_name=grModObj.project_name, \
          owner=grModObj.owner, is_private=form.cleaned_data["Project_Type"] == "private")
        ownedProjModObj.save()

      print "\nSaving all files complete..."

      # Make appropriate dirs if they dont already exist
      create_dir_struct([derivatives, graphs])

      # TEST #
      """
      derivatives = "/home/disa/test/build_test"
      graphs = derivatives
      proj_dir = derivatives
      invariant_loc = derivatives 
      # END TEST #
      """

      sendJobBeginEmail(email, invariants)
      task_build.delay(derivatives, graphs, graph_size, invariants, derivatives, email)
      request.session["success_msg"] =\
"""
Your job successfully launched. You should receive an email to confirm launch
and another when it upon job completion. <br/>
<i>The process may take several hours</i> if you selected to compute all invariants.
"""
      return HttpResponseRedirect(get_script_prefix()+"success")

  else:
    form = BuildGraphForm() # An empty, unbound form

  # Render the form
  return render_to_response(
      "buildgraph.html",
      {"buildGraphform": form},
      context_instance=RequestContext(request) 
  )

Example 162

Project: satchmo
Source File: contact.py
View license
def contact_info(request, **kwargs):
    """View which collects demographic information from customer."""

    #First verify that the cart exists and has items
    tempCart = Cart.objects.from_request(request)
    if tempCart.numItems == 0:
        return render_to_response('shop/checkout/empty_cart.html',
                                  context_instance=RequestContext(request))

    if not request.user.is_authenticated() and config_value('SHOP', 'AUTHENTICATION_REQUIRED'):
        url = urlresolvers.reverse('satchmo_checkout_auth_required')
        thisurl = urlresolvers.reverse('satchmo_checkout-step1')
        return http.HttpResponseRedirect(url + "?next=" + thisurl)

    init_data = {}
    shop = Config.objects.get_current()
    if request.user.is_authenticated():
        if request.user.email:
            init_data['email'] = request.user.email
        if request.user.first_name:
            init_data['first_name'] = request.user.first_name
        if request.user.last_name:
            init_data['last_name'] = request.user.last_name
    try:
        contact = Contact.objects.from_request(request, create=False)
    except Contact.DoesNotExist:
        contact = None

    try:
        order = Order.objects.from_request(request)
        if order.discount_code:
            init_data['discount'] = order.discount_code
    except Order.DoesNotExist:
        pass

    if request.method == "POST":
        new_data = request.POST.copy()
        if not tempCart.is_shippable:
            new_data['copy_address'] = True
        form = PaymentContactInfoForm(data=new_data, shop=shop, contact=contact, shippable=tempCart.is_shippable,
            initial=init_data, cart=tempCart)

        if form.is_valid():
            if contact is None and request.user and request.user.is_authenticated():
                contact = Contact(user=request.user)
            custID = form.save(request, cart=tempCart, contact=contact)
            request.session[CUSTOMER_ID] = custID

            modulename = new_data['paymentmethod']
            if not modulename.startswith('PAYMENT_'):
                modulename = 'PAYMENT_' + modulename
            paymentmodule = config_get_group(modulename)
            url = lookup_url(paymentmodule, 'satchmo_checkout-step2')
            return http.HttpResponseRedirect(url)
        else:
            log.debug("Form errors: %s", form.errors)
    else:
        if contact:
            #If a person has their contact info, make sure we populate it in the form
            for item in contact.__dict__.keys():
                init_data[item] = getattr(contact,item)
            if contact.shipping_address:
                for item in contact.shipping_address.__dict__.keys():
                    init_data["ship_"+item] = getattr(contact.shipping_address,item)
            if contact.billing_address:
                for item in contact.billing_address.__dict__.keys():
                    init_data[item] = getattr(contact.billing_address,item)
            if contact.primary_phone:
                init_data['phone'] = contact.primary_phone.phone
        else:
            # Allow them to login from this page.
            request.session.set_test_cookie()

        #Request additional init_data
        form_initialdata.send(sender=PaymentContactInfoForm, initial=init_data,
            contact=contact, cart=tempCart, shop=shop)

        form = PaymentContactInfoForm(
            shop=shop,
            contact=contact,
            shippable=tempCart.is_shippable,
            initial=init_data,
            cart=tempCart)

    if shop.in_country_only:
        only_country = shop.sales_country
    else:
        only_country = None

    context = RequestContext(request, {
        'form': form,
        'country': only_country,
        'paymentmethod_ct': len(form.fields['paymentmethod'].choices)
        })
    return render_to_response('shop/checkout/form.html',
                              context_instance=context)

Example 163

Project: newfies-dialer
Source File: views.py
View license
@permission_required('dialer_campaign.view_dashboard', login_url='/')
@login_required
def customer_dashboard(request, on_index=None):
    """Customer dashboard gives the following information

        * Total Campaigns contacts
        * Amount of contact reached today
        * Disposition of calls via pie chart
        * Call records & Duration of calls are shown on graph by days/hours

    **Attributes**:

        * ``template`` - frontend/dashboard.html
        * ``form`` - DashboardForm
    """
    logging.debug('Start Dashboard')
    # All campaign for logged in User
    campaign_id_list = Campaign.objects.values_list('id', flat=True).filter(user=request.user).order_by('id')

    # Contacts count which are active and belong to those phonebook(s) which is
    # associated with all campaign
    pb_active_contact_count = Contact.objects\
        .filter(phonebook__campaign__in=campaign_id_list, status=CONTACT_STATUS.ACTIVE).count()

    form = DashboardForm(request.user, request.POST or None)
    logging.debug('Got Campaign list')

    total_record = dict()
    total_duration_sum = 0
    total_billsec_sum = 0
    total_call_count = 0
    total_answered = 0
    total_not_answered = 0
    total_busy = 0
    total_cancel = 0
    total_congestion = 0
    total_failed = 0
    search_type = SEARCH_TYPE.D_Last_24_hours  # default Last 24 hours
    selected_campaign = ''

    if campaign_id_list:
        selected_campaign = campaign_id_list[0]  # default campaign id

    # selected_campaign should not be empty
    if selected_campaign:
        if form.is_valid():
            selected_campaign = request.POST['campaign']
            search_type = request.POST['search_type']

        end_date = datetime.utcnow().replace(tzinfo=utc)
        start_date = calculate_date(search_type)

        # date_length is used to do group by starting_date
        if int(search_type) >= SEARCH_TYPE.B_Last_7_days:  # all options except 30 days
            date_length = 13
            if int(search_type) == SEARCH_TYPE.C_Yesterday:  # yesterday
                tday = datetime.utcnow().replace(tzinfo=utc)
                start_date = datetime(tday.year, tday.month, tday.day, 0, 0, 0, 0)\
                    .replace(tzinfo=utc) - relativedelta(days=1)
                end_date = datetime(tday.year, tday.month, tday.day, 23, 59, 59, 999999)\
                    .replace(tzinfo=utc) - relativedelta(days=1)
            if int(search_type) >= SEARCH_TYPE.E_Last_12_hours:
                date_length = 16
        else:
            date_length = 10  # Last 30 days option

        select_data = {
            "starting_date": "SUBSTR(CAST(starting_date as CHAR(30)),1,%s)" % str(date_length)
        }

        # This calls list is used by pie chart
        calls = VoIPCall.objects\
            .filter(callrequest__campaign=selected_campaign,
                    duration__isnull=False,
                    user=request.user,
                    starting_date__range=(start_date, end_date))\
            .extra(select=select_data)\
            .values('starting_date', 'disposition')\
            .annotate(Count('starting_date'))\
            .order_by('starting_date')

        logging.debug('Aggregate VoIPCall')

        for i in calls:
            total_call_count += i['starting_date__count']
            if i['disposition'] == CALL_DISPOSITION.ANSWER or i['disposition'] == 'NORMAL_CLEARING':
                total_answered += i['starting_date__count']
            elif i['disposition'] == CALL_DISPOSITION.BUSY or i['disposition'] == 'USER_BUSY':
                total_busy += i['starting_date__count']
            elif i['disposition'] == CALL_DISPOSITION.NOANSWER or i['disposition'] == 'NO_ANSWER':
                total_not_answered += i['starting_date__count']
            elif i['disposition'] == CALL_DISPOSITION.CANCEL or i['disposition'] == 'ORIGINATOR_CANCEL':
                total_cancel += i['starting_date__count']
            elif i['disposition'] == CALL_DISPOSITION.CONGESTION or i['disposition'] == 'NORMAL_CIRCUIT_CONGESTION':
                total_congestion += i['starting_date__count']
            else:
                # VOIP CALL FAILED
                total_failed += i['starting_date__count']

        # following calls list is without disposition & group by call date
        calls = VoIPCall.objects\
            .filter(callrequest__campaign=selected_campaign,
                    duration__isnull=False,
                    user=request.user,
                    starting_date__range=(start_date, end_date))\
            .extra(select=select_data)\
            .values('starting_date')\
            .annotate(Sum('duration'))\
            .annotate(Sum('billsec'))\
            .annotate(Avg('duration'))\
            .annotate(Count('starting_date'))\
            .order_by('starting_date')

        logging.debug('Aggregate VoIPCall (2)')

        mintime = start_date
        maxtime = end_date
        calls_dict = {}
        calls_dict_with_min = {}

        for call in calls:
            total_duration_sum += call['duration__sum']
            total_billsec_sum += call['billsec__sum']
            if int(search_type) >= SEARCH_TYPE.B_Last_7_days:
                ctime = datetime(int(call['starting_date'][0:4]),
                                 int(call['starting_date'][5:7]),
                                 int(call['starting_date'][8:10]),
                                 int(call['starting_date'][11:13]),
                                 0,
                                 0,
                                 0).replace(tzinfo=utc)
                if int(search_type) >= SEARCH_TYPE.E_Last_12_hours:
                    ctime = datetime(int(call['starting_date'][0:4]),
                                     int(call['starting_date'][5:7]),
                                     int(call['starting_date'][8:10]),
                                     int(call['starting_date'][11:13]),
                                     int(call['starting_date'][14:16]),
                                     0,
                                     0).replace(tzinfo=utc)
            else:
                ctime = datetime(int(call['starting_date'][0:4]),
                                 int(call['starting_date'][5:7]),
                                 int(call['starting_date'][8:10]),
                                 0,
                                 0,
                                 0,
                                 0).replace(tzinfo=utc)
            if ctime > maxtime:
                maxtime = ctime
            elif ctime < mintime:
                mintime = ctime

            # all options except 30 days
            if int(search_type) >= SEARCH_TYPE.B_Last_7_days:
                calls_dict[int(ctime.strftime("%Y%m%d%H"))] =\
                    {
                        'call_count': call['starting_date__count'],
                        'duration_sum': call['duration__sum'],
                        'duration_avg': float(call['duration__avg']),
                }

                calls_dict_with_min[int(ctime.strftime("%Y%m%d%H%M"))] =\
                    {
                        'call_count': call['starting_date__count'],
                        'duration_sum': call['duration__sum'],
                        'duration_avg': float(call['duration__avg']),
                }
            else:
                # Last 30 days option
                calls_dict[int(ctime.strftime("%Y%m%d"))] =\
                    {
                        'call_count': call['starting_date__count'],
                        'duration_sum': call['duration__sum'],
                        'duration_avg': float(call['duration__avg']),
                }

        logging.debug('After Call Loops')

        dateList = date_range(mintime, maxtime, q=search_type)

        for date in dateList:
            inttime = int(date.strftime("%Y%m%d"))

            # last 7 days | yesterday | last 24 hrs
            if int(search_type) == SEARCH_TYPE.B_Last_7_days \
                or int(search_type) == SEARCH_TYPE.C_Yesterday \
                    or int(search_type) == SEARCH_TYPE.D_Last_24_hours:

                for option in range(0, 24):
                    day_time = int(str(inttime) + str(option).zfill(2))

                    graph_day = datetime(int(date.strftime("%Y")),
                                         int(date.strftime("%m")),
                                         int(date.strftime("%d")),
                                         int(str(option).zfill(2))).replace(tzinfo=utc)

                    dt = int(1000 * time.mktime(graph_day.timetuple()))
                    total_record[dt] = {
                        'call_count': 0,
                        'duration_sum': 0,
                        'duration_avg': 0.0,
                    }

                    if day_time in calls_dict.keys():
                        total_record[dt]['call_count'] += calls_dict[day_time]['call_count']
                        total_record[dt]['duration_sum'] += calls_dict[day_time]['duration_sum']
                        total_record[dt]['duration_avg'] += float(calls_dict[day_time]['duration_avg'])

            # last 12 hrs | last 6 hrs | last 1 hr
            elif (int(search_type) == SEARCH_TYPE.E_Last_12_hours
                  or int(search_type) == SEARCH_TYPE.F_Last_6_hours
                  or int(search_type) == SEARCH_TYPE.G_Last_hour):

                for hour in range(0, 24):
                    for minute in range(0, 60):
                        hr_time = int(str(inttime) + str(hour).zfill(2) + str(minute).zfill(2))

                        graph_day = datetime(int(date.strftime("%Y")),
                                             int(date.strftime("%m")),
                                             int(date.strftime("%d")),
                                             int(str(hour).zfill(2)),
                                             int(str(minute).zfill(2))).replace(tzinfo=utc)

                        dt = int(1000 * time.mktime(graph_day.timetuple()))
                        total_record[dt] = {
                            'call_count': 0,
                            'duration_sum': 0,
                            'duration_avg': 0.0,
                        }

                        if hr_time in calls_dict_with_min.keys():
                            total_record[dt]['call_count'] += calls_dict_with_min[hr_time]['call_count']
                            total_record[dt]['duration_sum'] += calls_dict_with_min[hr_time]['duration_sum']
                            total_record[dt]['duration_avg'] += float(calls_dict_with_min[hr_time]['duration_avg'])
            else:
                # Default: Last 30 days option
                graph_day = datetime(int(date.strftime("%Y")),
                                     int(date.strftime("%m")),
                                     int(date.strftime("%d"))).replace(tzinfo=utc)
                dt = int(1000 * time.mktime(graph_day.timetuple()))
                total_record[dt] = {
                    'call_count': 0,
                    'duration_sum': 0,
                    'duration_avg': 0,
                }
                if inttime in calls_dict.keys():
                    total_record[dt]['call_count'] += calls_dict[inttime]['call_count']
                    total_record[dt]['duration_sum'] += calls_dict[inttime]['duration_sum']
                    total_record[dt]['duration_avg'] += float(calls_dict[inttime]['duration_avg'])

    logging.debug('After dateList Loops')

    # sorting on date col
    total_record = total_record.items()
    total_record = sorted(total_record, key=lambda k: k[0])

    # lineplusbarwithfocuschart
    final_charttype = "linePlusBarChart"
    xdata = []
    ydata = []
    ydata2 = []
    for i in total_record:
        xdata.append(i[0])
        ydata.append(i[1]['call_count'])
        ydata2.append(i[1]['duration_sum'])

    tooltip_date = "%d %b %y %H:%M %p"
    kwargs1 = {}
    kwargs1['bar'] = True
    extra_serie1 = {"tooltip": {"y_start": "", "y_end": " calls"}, "date_format": tooltip_date}
    extra_serie2 = {"tooltip": {"y_start": "", "y_end": " sec"}, "date_format": tooltip_date}

    final_chartdata = {
        'x': xdata,
        'name1': 'Calls', 'y1': ydata, 'extra1': extra_serie1, 'kwargs1': kwargs1,
        'name2': 'Duration', 'y2': ydata2, 'extra2': extra_serie2,
    }

    # Contacts which are successfully called for running campaign
    reached_contact = 0
    if campaign_id_list:
        tday = datetime.utcnow().replace(tzinfo=utc)
        start_date = datetime(tday.year, tday.month, tday.day, 0, 0, 0, 0).replace(tzinfo=utc)
        end_date = datetime(tday.year, tday.month, tday.day, 23, 59, 59, 999999).replace(tzinfo=utc)
        reached_contact = Subscriber.objects\
            .filter(campaign_id__in=campaign_id_list,  # status=5,
                    updated_date__range=(start_date, end_date))\
            .count()

    # PieChart
    hangup_analytic_charttype = "pieChart"
    xdata = []
    ydata = []
    hangup_analytic_chartdata = {'x': xdata, 'y1': ydata}
    if total_call_count != 0:
        for i in CALL_DISPOSITION:
            xdata.append(i[0])

        # Y-axis order depend upon CALL_DISPOSITION
        # 'ANSWER', 'BUSY', 'CANCEL', 'CONGESTION', 'FAILED', 'NOANSWER'
        ydata = [percentage(total_answered, total_call_count),
                 percentage(total_busy, total_call_count),
                 percentage(total_cancel, total_call_count),
                 percentage(total_congestion, total_call_count),
                 percentage(total_failed, total_call_count),
                 percentage(total_not_answered, total_call_count)]

        color_list = [
            COLOR_DISPOSITION['ANSWER'],
            COLOR_DISPOSITION['BUSY'],
            COLOR_DISPOSITION['CANCEL'],
            COLOR_DISPOSITION['CONGESTION'],
            COLOR_DISPOSITION['FAILED'],
            COLOR_DISPOSITION['NOANSWER'],
        ]

        extra_serie = {"tooltip": {"y_start": "", "y_end": " %"},
                       "color_list": color_list}
        hangup_analytic_chartdata = {'x': xdata, 'y1': ydata, 'extra1': extra_serie}

    data = {
        'form': form,
        'campaign_phonebook_active_contact_count': pb_active_contact_count,
        'reached_contact': reached_contact,
        'total_duration_sum': total_duration_sum,
        'total_billsec_sum': total_billsec_sum,
        'total_call_count': total_call_count,
        'total_answered': total_answered,
        'total_not_answered': total_not_answered,
        'total_busy': total_busy,
        'total_cancel': total_cancel,
        'total_congestion': total_congestion,
        'total_failed': total_failed,
        'answered_color': COLOR_DISPOSITION['ANSWER'],
        'busy_color': COLOR_DISPOSITION['BUSY'],
        'not_answered_color': COLOR_DISPOSITION['NOANSWER'],
        'cancel_color': COLOR_DISPOSITION['CANCEL'],
        'congestion_color': COLOR_DISPOSITION['CONGESTION'],
        'failed_color': COLOR_DISPOSITION['FAILED'],
        'CALL_DISPOSITION': CALL_DISPOSITION,
        'hangup_analytic_chartdata': hangup_analytic_chartdata,
        'hangup_analytic_charttype': hangup_analytic_charttype,
        'hangup_chartcontainer': 'piechart_container',
        'hangup_extra': {
            'x_is_date': False,
            'x_axis_format': '',
            'tag_script_js': True,
            'jquery_on_ready': True,
        },
        'final_chartdata': final_chartdata,
        'final_charttype': final_charttype,
        'final_chartcontainer': 'lineplusbarwithfocuschart_container',
        'final_extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %Y',
            'tag_script_js': True,
            'jquery_on_ready': True,
            'resize': True,
            'focus_enable': True,
        }
    }
    if on_index == 'yes':
        return data
    return render_to_response('frontend/dashboard.html', data, context_instance=RequestContext(request))

Example 164

Project: foodnetwork
Source File: views.py
View license
@login_required
def planning_table(request, member_id, list_type, from_date, to_date):
    member = get_object_or_404(Party, pk=member_id)
    role = "producer"
    plan_type = "Production"
    if member.is_customer():
        role = "consumer"
        plan_type = "Consumption"

    try:
        from_date = datetime.datetime(*time.strptime(from_date, '%Y_%m_%d')[0:5]).date()
        to_date = datetime.datetime(*time.strptime(to_date, '%Y_%m_%d')[0:5]).date()
    except ValueError:
            raise Http404
    # force from_date to Monday, to_date to Sunday
    from_date = from_date - datetime.timedelta(days=datetime.date.weekday(from_date))
    to_date = to_date - datetime.timedelta(days=datetime.date.weekday(to_date)+1)
    to_date = to_date + datetime.timedelta(days=7)
    products = None
    if list_type == "M":
        if role == "consumer":
            products = CustomerProduct.objects.filter(customer=member, planned=True)
        else:
            products = ProducerProduct.objects.filter(producer=member, planned=True)
    if not products:
        products = Product.objects.filter(plannable=True)
        list_type = "A"
    plan_table = plan_weeks(member, products, from_date, to_date)
    forms = create_weekly_plan_forms(plan_table.rows, data=request.POST or None)
    if request.method == "POST":
        #import pdb; pdb.set_trace()
        for row in forms:
            if row.formset.is_valid():
                for form in row.formset.forms:
                    data = form.cleaned_data
                    qty = data['quantity']
                    plan_id = data['plan_id']
                    from_dt = data['from_date']
                    to_dt = data['to_date']
                    product_id = data['product_id']
                    plan = None
                    if plan_id:
                        # what if plan was changed by prev cell?
                        plan = ProductPlan.objects.get(id=plan_id)
                        if plan.to_date < from_dt or plan.from_date > to_dt:
                            plan = None
                    if qty:
                        if plan:
                            #import pdb; pdb.set_trace()
                            if not qty == plan.quantity:
                                #import pdb; pdb.set_trace()
                                if plan.from_date >= from_dt and plan.to_date <= to_dt:
                                    plan.quantity = qty
                                    plan.save()
                                else:
                                    if plan.from_date < from_dt:
                                        new_to_dt = from_dt - datetime.timedelta(days=1)
                                        earlier_plan = ProductPlan(
                                            member=plan.member,
                                            product=plan.product,
                                            quantity=plan.quantity,
                                            from_date=plan.from_date,
                                            to_date=new_to_dt,
                                            role=plan.role,
                                            inventoried=plan.inventoried,
                                            distributor=plan.distributor,
                                        )
                                        earlier_plan.save()
                                    if plan.to_date > to_dt:
                                        new_plan = ProductPlan(
                                            member=plan.member,
                                            product=plan.product,
                                            quantity=qty,
                                            from_date=from_dt,
                                            to_date=to_dt,
                                            role=plan.role,
                                            inventoried=plan.inventoried,
                                            distributor=plan.distributor,
                                        )
                                        new_plan.save()
                                        plan.from_date = to_dt + datetime.timedelta(days=1)
                                        plan.save()
                                    else:
                                        plan.from_date=from_dt
                                        plan.quantity=qty
                                        plan.save()      
                        else:
                            product = Product.objects.get(id=product_id)
                            new_plan = ProductPlan(
                                member=member,
                                product=product,
                                quantity=qty,
                                from_date=from_dt,
                                to_date=to_dt,
                                role=role,
                                #inventoried=True,
                                #distributor,
                            )
                            new_plan.save()
                            #import pdb; pdb.set_trace()
                            if role == "producer":
                                listed_product, created = ProducerProduct.objects.get_or_create(
                                    product=product, producer=member)
                            #elif role == "consumer":
                                #todo: shd these be auto-created at all?
                                # and if so, what MemberProductList?
                            #    listed_product, created = CustomerProduct.objects.get_or_create(
                            #        product=product, customer=member)

                    else:
                        if plan:
                            if plan.from_date >= from_dt and plan.to_date <= to_dt:
                                #pass
                                plan.delete()
                            else:
                                #import pdb; pdb.set_trace()
                                if plan.to_date > to_dt:
                                    early_from_dt = plan.from_date              
                                    if plan.from_date < from_dt:
                                        early_to_dt = from_dt - datetime.timedelta(days=1)
                                        earlier_plan = ProductPlan(
                                            member=plan.member,
                                            product=plan.product,
                                            quantity=plan.quantity,
                                            from_date=early_from_dt,
                                            to_date=early_to_dt,
                                            role=plan.role,
                                            inventoried=plan.inventoried,
                                            distributor=plan.distributor,
                                         )
                                        earlier_plan.save()
                                    plan.from_date = to_dt + datetime.timedelta(days=1)
                                    plan.save()
                                else:
                                    plan.to_date= from_dt - datetime.timedelta(days=1)
                                    plan.save()
        from_date = from_date.strftime('%Y_%m_%d')
        to_date = to_date.strftime('%Y_%m_%d')
        return HttpResponseRedirect('/%s/%s/%s/%s/'
                    % ('customer/customerplans', from_date, to_date, member_id))
    return render_to_response('distribution/planning_table.html', 
        {
            'from_date': from_date,
            'to_date': to_date,
            'plan_table': plan_table,
            'forms': forms,
            'plan_type': plan_type,
            'member': member,
            'list_type': list_type,
            'tabnav': "customer/customer_tabnav.html",
        }, context_instance=RequestContext(request))

Example 165

Project: newfies-dialer
Source File: views.py
View license
@permission_required('dialer_campaign.view_dashboard', login_url='/')
@login_required
def customer_dashboard(request, on_index=None):
    """Customer dashboard gives the following information

        * Total Campaigns contacts
        * Amount of contact reached today
        * Disposition of calls via pie chart
        * Call records & Duration of calls are shown on graph by days/hours

    **Attributes**:

        * ``template`` - frontend/dashboard.html
        * ``form`` - DashboardForm
    """
    logging.debug('Start Dashboard')
    # All campaign for logged in User
    campaign_id_list = Campaign.objects.values_list('id', flat=True).filter(user=request.user).order_by('id')

    # Contacts count which are active and belong to those phonebook(s) which is
    # associated with all campaign
    pb_active_contact_count = Contact.objects\
        .filter(phonebook__campaign__in=campaign_id_list, status=CONTACT_STATUS.ACTIVE).count()

    form = DashboardForm(request.user, request.POST or None)
    logging.debug('Got Campaign list')

    total_record = dict()
    total_duration_sum = 0
    total_billsec_sum = 0
    total_call_count = 0
    total_answered = 0
    total_not_answered = 0
    total_busy = 0
    total_cancel = 0
    total_congestion = 0
    total_failed = 0
    search_type = SEARCH_TYPE.D_Last_24_hours  # default Last 24 hours
    selected_campaign = ''

    if campaign_id_list:
        selected_campaign = campaign_id_list[0]  # default campaign id

    # selected_campaign should not be empty
    if selected_campaign:
        if form.is_valid():
            selected_campaign = request.POST['campaign']
            search_type = request.POST['search_type']

        end_date = datetime.utcnow().replace(tzinfo=utc)
        start_date = calculate_date(search_type)

        # date_length is used to do group by starting_date
        if int(search_type) >= SEARCH_TYPE.B_Last_7_days:  # all options except 30 days
            date_length = 13
            if int(search_type) == SEARCH_TYPE.C_Yesterday:  # yesterday
                tday = datetime.utcnow().replace(tzinfo=utc)
                start_date = datetime(tday.year, tday.month, tday.day, 0, 0, 0, 0)\
                    .replace(tzinfo=utc) - relativedelta(days=1)
                end_date = datetime(tday.year, tday.month, tday.day, 23, 59, 59, 999999)\
                    .replace(tzinfo=utc) - relativedelta(days=1)
            if int(search_type) >= SEARCH_TYPE.E_Last_12_hours:
                date_length = 16
        else:
            date_length = 10  # Last 30 days option

        select_data = {
            "starting_date": "SUBSTR(CAST(starting_date as CHAR(30)),1,%s)" % str(date_length)
        }

        # This calls list is used by pie chart
        calls = VoIPCall.objects\
            .filter(callrequest__campaign=selected_campaign,
                    duration__isnull=False,
                    user=request.user,
                    starting_date__range=(start_date, end_date))\
            .extra(select=select_data)\
            .values('starting_date', 'disposition')\
            .annotate(Count('starting_date'))\
            .order_by('starting_date')

        logging.debug('Aggregate VoIPCall')

        for i in calls:
            total_call_count += i['starting_date__count']
            if i['disposition'] == CALL_DISPOSITION.ANSWER or i['disposition'] == 'NORMAL_CLEARING':
                total_answered += i['starting_date__count']
            elif i['disposition'] == CALL_DISPOSITION.BUSY or i['disposition'] == 'USER_BUSY':
                total_busy += i['starting_date__count']
            elif i['disposition'] == CALL_DISPOSITION.NOANSWER or i['disposition'] == 'NO_ANSWER':
                total_not_answered += i['starting_date__count']
            elif i['disposition'] == CALL_DISPOSITION.CANCEL or i['disposition'] == 'ORIGINATOR_CANCEL':
                total_cancel += i['starting_date__count']
            elif i['disposition'] == CALL_DISPOSITION.CONGESTION or i['disposition'] == 'NORMAL_CIRCUIT_CONGESTION':
                total_congestion += i['starting_date__count']
            else:
                # VOIP CALL FAILED
                total_failed += i['starting_date__count']

        # following calls list is without disposition & group by call date
        calls = VoIPCall.objects\
            .filter(callrequest__campaign=selected_campaign,
                    duration__isnull=False,
                    user=request.user,
                    starting_date__range=(start_date, end_date))\
            .extra(select=select_data)\
            .values('starting_date')\
            .annotate(Sum('duration'))\
            .annotate(Sum('billsec'))\
            .annotate(Avg('duration'))\
            .annotate(Count('starting_date'))\
            .order_by('starting_date')

        logging.debug('Aggregate VoIPCall (2)')

        mintime = start_date
        maxtime = end_date
        calls_dict = {}
        calls_dict_with_min = {}

        for call in calls:
            total_duration_sum += call['duration__sum']
            total_billsec_sum += call['billsec__sum']
            if int(search_type) >= SEARCH_TYPE.B_Last_7_days:
                ctime = datetime(int(call['starting_date'][0:4]),
                                 int(call['starting_date'][5:7]),
                                 int(call['starting_date'][8:10]),
                                 int(call['starting_date'][11:13]),
                                 0,
                                 0,
                                 0).replace(tzinfo=utc)
                if int(search_type) >= SEARCH_TYPE.E_Last_12_hours:
                    ctime = datetime(int(call['starting_date'][0:4]),
                                     int(call['starting_date'][5:7]),
                                     int(call['starting_date'][8:10]),
                                     int(call['starting_date'][11:13]),
                                     int(call['starting_date'][14:16]),
                                     0,
                                     0).replace(tzinfo=utc)
            else:
                ctime = datetime(int(call['starting_date'][0:4]),
                                 int(call['starting_date'][5:7]),
                                 int(call['starting_date'][8:10]),
                                 0,
                                 0,
                                 0,
                                 0).replace(tzinfo=utc)
            if ctime > maxtime:
                maxtime = ctime
            elif ctime < mintime:
                mintime = ctime

            # all options except 30 days
            if int(search_type) >= SEARCH_TYPE.B_Last_7_days:
                calls_dict[int(ctime.strftime("%Y%m%d%H"))] =\
                    {
                        'call_count': call['starting_date__count'],
                        'duration_sum': call['duration__sum'],
                        'duration_avg': float(call['duration__avg']),
                }

                calls_dict_with_min[int(ctime.strftime("%Y%m%d%H%M"))] =\
                    {
                        'call_count': call['starting_date__count'],
                        'duration_sum': call['duration__sum'],
                        'duration_avg': float(call['duration__avg']),
                }
            else:
                # Last 30 days option
                calls_dict[int(ctime.strftime("%Y%m%d"))] =\
                    {
                        'call_count': call['starting_date__count'],
                        'duration_sum': call['duration__sum'],
                        'duration_avg': float(call['duration__avg']),
                }

        logging.debug('After Call Loops')

        dateList = date_range(mintime, maxtime, q=search_type)

        for date in dateList:
            inttime = int(date.strftime("%Y%m%d"))

            # last 7 days | yesterday | last 24 hrs
            if int(search_type) == SEARCH_TYPE.B_Last_7_days \
                or int(search_type) == SEARCH_TYPE.C_Yesterday \
                    or int(search_type) == SEARCH_TYPE.D_Last_24_hours:

                for option in range(0, 24):
                    day_time = int(str(inttime) + str(option).zfill(2))

                    graph_day = datetime(int(date.strftime("%Y")),
                                         int(date.strftime("%m")),
                                         int(date.strftime("%d")),
                                         int(str(option).zfill(2))).replace(tzinfo=utc)

                    dt = int(1000 * time.mktime(graph_day.timetuple()))
                    total_record[dt] = {
                        'call_count': 0,
                        'duration_sum': 0,
                        'duration_avg': 0.0,
                    }

                    if day_time in calls_dict.keys():
                        total_record[dt]['call_count'] += calls_dict[day_time]['call_count']
                        total_record[dt]['duration_sum'] += calls_dict[day_time]['duration_sum']
                        total_record[dt]['duration_avg'] += float(calls_dict[day_time]['duration_avg'])

            # last 12 hrs | last 6 hrs | last 1 hr
            elif (int(search_type) == SEARCH_TYPE.E_Last_12_hours
                  or int(search_type) == SEARCH_TYPE.F_Last_6_hours
                  or int(search_type) == SEARCH_TYPE.G_Last_hour):

                for hour in range(0, 24):
                    for minute in range(0, 60):
                        hr_time = int(str(inttime) + str(hour).zfill(2) + str(minute).zfill(2))

                        graph_day = datetime(int(date.strftime("%Y")),
                                             int(date.strftime("%m")),
                                             int(date.strftime("%d")),
                                             int(str(hour).zfill(2)),
                                             int(str(minute).zfill(2))).replace(tzinfo=utc)

                        dt = int(1000 * time.mktime(graph_day.timetuple()))
                        total_record[dt] = {
                            'call_count': 0,
                            'duration_sum': 0,
                            'duration_avg': 0.0,
                        }

                        if hr_time in calls_dict_with_min.keys():
                            total_record[dt]['call_count'] += calls_dict_with_min[hr_time]['call_count']
                            total_record[dt]['duration_sum'] += calls_dict_with_min[hr_time]['duration_sum']
                            total_record[dt]['duration_avg'] += float(calls_dict_with_min[hr_time]['duration_avg'])
            else:
                # Default: Last 30 days option
                graph_day = datetime(int(date.strftime("%Y")),
                                     int(date.strftime("%m")),
                                     int(date.strftime("%d"))).replace(tzinfo=utc)
                dt = int(1000 * time.mktime(graph_day.timetuple()))
                total_record[dt] = {
                    'call_count': 0,
                    'duration_sum': 0,
                    'duration_avg': 0,
                }
                if inttime in calls_dict.keys():
                    total_record[dt]['call_count'] += calls_dict[inttime]['call_count']
                    total_record[dt]['duration_sum'] += calls_dict[inttime]['duration_sum']
                    total_record[dt]['duration_avg'] += float(calls_dict[inttime]['duration_avg'])

    logging.debug('After dateList Loops')

    # sorting on date col
    total_record = total_record.items()
    total_record = sorted(total_record, key=lambda k: k[0])

    # lineplusbarwithfocuschart
    final_charttype = "linePlusBarChart"
    xdata = []
    ydata = []
    ydata2 = []
    for i in total_record:
        xdata.append(i[0])
        ydata.append(i[1]['call_count'])
        ydata2.append(i[1]['duration_sum'])

    tooltip_date = "%d %b %y %H:%M %p"
    kwargs1 = {}
    kwargs1['bar'] = True
    extra_serie1 = {"tooltip": {"y_start": "", "y_end": " calls"}, "date_format": tooltip_date}
    extra_serie2 = {"tooltip": {"y_start": "", "y_end": " sec"}, "date_format": tooltip_date}

    final_chartdata = {
        'x': xdata,
        'name1': 'Calls', 'y1': ydata, 'extra1': extra_serie1, 'kwargs1': kwargs1,
        'name2': 'Duration', 'y2': ydata2, 'extra2': extra_serie2,
    }

    # Contacts which are successfully called for running campaign
    reached_contact = 0
    if campaign_id_list:
        tday = datetime.utcnow().replace(tzinfo=utc)
        start_date = datetime(tday.year, tday.month, tday.day, 0, 0, 0, 0).replace(tzinfo=utc)
        end_date = datetime(tday.year, tday.month, tday.day, 23, 59, 59, 999999).replace(tzinfo=utc)
        reached_contact = Subscriber.objects\
            .filter(campaign_id__in=campaign_id_list,  # status=5,
                    updated_date__range=(start_date, end_date))\
            .count()

    # PieChart
    hangup_analytic_charttype = "pieChart"
    xdata = []
    ydata = []
    hangup_analytic_chartdata = {'x': xdata, 'y1': ydata}
    if total_call_count != 0:
        for i in CALL_DISPOSITION:
            xdata.append(i[0])

        # Y-axis order depend upon CALL_DISPOSITION
        # 'ANSWER', 'BUSY', 'CANCEL', 'CONGESTION', 'FAILED', 'NOANSWER'
        ydata = [percentage(total_answered, total_call_count),
                 percentage(total_busy, total_call_count),
                 percentage(total_cancel, total_call_count),
                 percentage(total_congestion, total_call_count),
                 percentage(total_failed, total_call_count),
                 percentage(total_not_answered, total_call_count)]

        color_list = [
            COLOR_DISPOSITION['ANSWER'],
            COLOR_DISPOSITION['BUSY'],
            COLOR_DISPOSITION['CANCEL'],
            COLOR_DISPOSITION['CONGESTION'],
            COLOR_DISPOSITION['FAILED'],
            COLOR_DISPOSITION['NOANSWER'],
        ]

        extra_serie = {"tooltip": {"y_start": "", "y_end": " %"},
                       "color_list": color_list}
        hangup_analytic_chartdata = {'x': xdata, 'y1': ydata, 'extra1': extra_serie}

    data = {
        'form': form,
        'campaign_phonebook_active_contact_count': pb_active_contact_count,
        'reached_contact': reached_contact,
        'total_duration_sum': total_duration_sum,
        'total_billsec_sum': total_billsec_sum,
        'total_call_count': total_call_count,
        'total_answered': total_answered,
        'total_not_answered': total_not_answered,
        'total_busy': total_busy,
        'total_cancel': total_cancel,
        'total_congestion': total_congestion,
        'total_failed': total_failed,
        'answered_color': COLOR_DISPOSITION['ANSWER'],
        'busy_color': COLOR_DISPOSITION['BUSY'],
        'not_answered_color': COLOR_DISPOSITION['NOANSWER'],
        'cancel_color': COLOR_DISPOSITION['CANCEL'],
        'congestion_color': COLOR_DISPOSITION['CONGESTION'],
        'failed_color': COLOR_DISPOSITION['FAILED'],
        'CALL_DISPOSITION': CALL_DISPOSITION,
        'hangup_analytic_chartdata': hangup_analytic_chartdata,
        'hangup_analytic_charttype': hangup_analytic_charttype,
        'hangup_chartcontainer': 'piechart_container',
        'hangup_extra': {
            'x_is_date': False,
            'x_axis_format': '',
            'tag_script_js': True,
            'jquery_on_ready': True,
        },
        'final_chartdata': final_chartdata,
        'final_charttype': final_charttype,
        'final_chartcontainer': 'lineplusbarwithfocuschart_container',
        'final_extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %Y',
            'tag_script_js': True,
            'jquery_on_ready': True,
            'resize': True,
            'focus_enable': True,
        }
    }
    if on_index == 'yes':
        return data
    return render_to_response('frontend/dashboard.html', data, context_instance=RequestContext(request))

Example 166

Project: AuShadha
Source File: views.py
View license
@login_required
def social_history_edit(request, social_history_id = None):

    if request.user:
        user = request.user

        try:
          if social_history_id:
            social_history_id = int(social_history_id)
          else:
            social_history_id = int(request.GET.get('social_history_id'))
          social_history_obj = SocialHistory.objects.get(pk=social_history_id)
          patient_detail_obj = social_history_obj.patient_detail

          if not getattr(patient_detail_obj, 'urls',None):
            patient_detail_obj.save()

          if not getattr(social_history_obj,'urls',None):
            social_history_obj.save()
            urls  = social_history_obj.urls
          else:
            urls  = social_history_obj.urls

        except ValueError or AttributeError or TypeError:
            raise Http404("BadRequest: Server Error")
        except SocialHistory.DoesNotExist:
            raise Http404("BadRequest: Requested Patient SocialHistory Data DoesNotExist")

        if request.method == "GET" and request.is_ajax():
                social_history_form = SocialHistoryForm(instance=social_history_obj)
                patient_detail_obj = social_history_obj.patient_detail
                addData = {
                    "marital_status": social_history_obj.marital_status,
                    "marital_status_notes": social_history_obj.marital_status_notes,
                    "occupation": social_history_obj.occupation,
                    "occupation_notes": social_history_obj.occupation_notes,
                    "exercise": social_history_obj.exercise,
                    "exercise_notes": social_history_obj.exercise_notes,
                    "diet": social_history_obj.diet,
                    "diet_notes": social_history_obj.diet_notes,
                    "home_occupants": social_history_obj.home_occupants,
                    "home_occupants_notes": social_history_obj.home_occupants_notes,
                    "pets": social_history_obj.pets,
                    "pets_notes": social_history_obj.pets_notes,
                    "alcohol": social_history_obj.alcohol,
                    "alcohol_no": social_history_obj.alcohol_no,
                    "alcohol_notes": social_history_obj.alcohol_notes,
                    "tobacco": social_history_obj.tobacco,
                    "tobacco_no": social_history_obj.tobacco_no,
                    "tobacco_notes": social_history_obj.tobacco_notes,
                    "drug_abuse": social_history_obj.drug_abuse,
                    "drug_abuse_notes": social_history_obj.drug_abuse_notes,
                    "sexual_preference": social_history_obj.sexual_preference,
                    "sexual_preference_notes": social_history_obj.sexual_preference_notes,
                    "current_events": social_history_obj.current_events
                }
                variable = RequestContext(request,
                                          {"user": user,
                                           "patient_detail_obj": patient_detail_obj,
                                           "social_history_form": social_history_form,
                                           "social_history_obj": social_history_obj,
                                           "addData": addData,
                                           'action': urls['edit'],
                                           'button_label': "Edit",
                                           'canDel': True,
                                           'addUrl': None,
                                           'editUrl': urls['edit'],
                                           'delUrl': urls['del'],
                                           })
                return render_to_response('social_history/add_or_edit_form.html', variable)

        elif request.method == 'POST' and request.is_ajax():
                copy_post = request.POST.copy()
                copy_post['home_occupants'] = ",".join(copy_post.getlist('home_occupants'))
                copy_post['pets'] = ",".join(copy_post.getlist('pets'))
                social_history_form = SocialHistoryForm(copy_post, instance=social_history_obj)
                patient_detail_obj = social_history_obj.patient_detail

                if social_history_form.is_valid():
                    social_history_obj = social_history_form.save()
                    success = True
                    error_message = "SocialHistory Data Edited Successfully"
                    form_errors = ''
                    addData = {
                        "marital_status": social_history_obj.marital_status,
                        "marital_status_notes": social_history_obj.marital_status_notes,
                        "occupation": social_history_obj.occupation,
                        "occupation_notes": social_history_obj.occupation_notes,
                        "exercise": social_history_obj.exercise,
                        "exercise_notes": social_history_obj.exercise_notes,
                        "diet": social_history_obj.diet_notes,
                        "home_occupants": social_history_obj.home_occupants,
                        "home_occupants_notes": social_history_obj.home_occupants_notes,
                        "pets": social_history_obj.pets,
                        "pets_notes": social_history_obj.pets_notes,
                        "alcohol": social_history_obj.alcohol,
                        "alcohol_no": social_history_obj.alcohol_no,
                        "alcohol_notes": social_history_obj.alcohol_notes,
                        "tobacco": social_history_obj.tobacco,
                        "tobacco_no": social_history_obj.tobacco_no,
                        "tobacco_notes": social_history_obj.tobacco_notes,
                        "drug_abuse": social_history_obj.drug_abuse,
                        "drug_abuse_notes": social_history_obj.drug_abuse_notes,
                        "sexual_preference": social_history_obj.sexual_preference,
                        "sexual_preference_notes": social_history_obj.sexual_preference_notes,
                        "current_events": social_history_obj.current_events
                    }
                    data = {'success': success,
                            'error_message': error_message,
                            'form_errors': form_errors,
                            "addData": addData
                            }
                else:
                    data = {'success': False, 
                            'error_message': aumodelformerrorformatter_factory(social_history_form), 
                            'form_errors':error_message,
                            'addData':None
                            }
                jsondata = json.dumps(data)
                return HttpResponse(jsondata, content_type='application/json')

        else:
            raise Http404("BadRequest: Unsupported Request Method")

Example 167

Project: newfies-dialer
Source File: views.py
View license
@permission_required('mod_sms.view_sms_dashboard', login_url='/')
@login_required
def sms_dashboard(request, on_index=None):
    """SMS dashboard gives the following information

        * No of SMSCampaigns for logged in user
        * Total phonebook contacts
        * Total SMSCampaigns contacts
        * Amount of contact reached today
        * Disposition of sms via pie chart
        * SMS count shown on graph by days/hours

    **Attributes**:

        * ``template`` - mod_sms/sms_dashboard.html
        * ``form`` - SMSDashboardForm
    """
    # All sms_campaign for logged in User
    sms_campaign_id_list = SMSCampaign.objects.values_list('id', flat=True).filter(user=request.user).order_by('id')

    # Contacts count which are active and belong to those phonebook(s) which is
    # associated with all sms campaign
    pb_active_contact_count = Contact.objects.filter(
        phonebook__smscampaign__in=sms_campaign_id_list,
        status=CONTACT_STATUS.ACTIVE).count()

    form = SMSDashboardForm(request.user, request.POST or None)

    total_record = dict()
    total_sms_count = 0
    total_unsent = 0
    total_sent = 0
    total_delivered = 0
    total_failed = 0
    total_no_route = 0
    total_unauthorized = 0

    select_graph_for = 'sms count'  # default
    search_type = SEARCH_TYPE.D_Last_24_hours  # default Last 24 hours
    selected_sms_campaign = ''

    if sms_campaign_id_list:
        selected_sms_campaign = sms_campaign_id_list[0]  # default sms campaign id

    # selected_sms_campaign should not be empty
    if selected_sms_campaign:

        if form.is_valid():
            selected_sms_campaign = request.POST['smscampaign']
            search_type = request.POST['search_type']

        end_date = datetime.utcnow().replace(tzinfo=utc)
        start_date = calculate_date(search_type)

        # date_length is used to do group by starting_date
        if int(search_type) >= SEARCH_TYPE.B_Last_7_days:  # all options except 30 days
            date_length = 13
            if int(search_type) == SEARCH_TYPE.C_Yesterday:  # yesterday
                now = datetime.utcnow().replace(tzinfo=utc)
                start_date = datetime(now.year, now.month, now.day, 0, 0, 0, 0).replace(tzinfo=utc) \
                    - relativedelta(days=1)
                end_date = datetime(now.year, now.month, now.day, 23, 59, 59, 999999).replace(tzinfo=utc) \
                    - relativedelta(days=1)
            if int(search_type) >= SEARCH_TYPE.E_Last_12_hours:
                date_length = 16
        else:
            date_length = 10  # Last 30 days option

        select_data = {
            "send_date": "SUBSTR(CAST(send_date as CHAR(30)),1," + str(date_length) + ")"}

        # This calls list is used by pie chart
        list_sms = SMSMessage.objects.filter(
            sender=request.user,
            sms_campaign_id=selected_sms_campaign,
            send_date__range=(start_date, end_date))\
            .extra(select=select_data)\
            .values('send_date', 'status')\
            .annotate(Count('send_date'))\
            .order_by('send_date')

        for i in list_sms:
            # convert unicode date string into date
            if i['status'] == 'Unsent':
                total_unsent += i['send_date__count']
            elif i['status'] == 'Sent':
                total_sent += i['send_date__count']
            elif i['status'] == 'Delivered':
                total_delivered += i['send_date__count']
            elif i['status'] == 'Failed':
                total_failed += i['send_date__count']
            elif i['status'] == 'No_Route':
                total_no_route += i['send_date__count']
            else:
                total_unauthorized += i['send_date__count']  # Unauthorized

            total_sms_count += i['send_date__count']

        list_sms = SMSMessage.objects.filter(
            sender=request.user,
            sms_campaign_id=selected_sms_campaign,
            send_date__range=(start_date, end_date))\
            .extra(select=select_data).values('send_date')\
            .annotate(Count('send_date')).order_by('send_date')

        mintime = start_date
        maxtime = end_date
        sms_dict = {}
        sms_dict_with_min = {}

        for data in list_sms:
            if int(search_type) >= SEARCH_TYPE.B_Last_7_days:
                ctime = datetime(int(data['send_date'][0:4]),
                                 int(data['send_date'][5:7]),
                                 int(data['send_date'][8:10]),
                                 int(data['send_date'][11:13]),
                                 0, 0, 0).replace(tzinfo=utc)
                if int(search_type) >= SEARCH_TYPE.E_Last_12_hours:
                    ctime = datetime(int(data['send_date'][0:4]),
                                     int(data['send_date'][5:7]),
                                     int(data['send_date'][8:10]),
                                     int(data['send_date'][11:13]),
                                     int(data['send_date'][14:16]),
                                     0, 0).replace(tzinfo=utc)
            else:
                ctime = datetime(int(data['send_date'][0:4]),
                                 int(data['send_date'][5:7]),
                                 int(data['send_date'][8:10]),
                                 0, 0, 0, 0).replace(tzinfo=utc)
            if ctime > maxtime:
                maxtime = ctime
            elif ctime < mintime:
                mintime = ctime

            # all options except 30 days
            if int(search_type) >= SEARCH_TYPE.B_Last_7_days:
                sms_dict[int(ctime.strftime("%Y%m%d%H"))] = {
                    'sms_count': data['send_date__count']
                }
                sms_dict_with_min[int(ctime.strftime("%Y%m%d%H%M"))] = {
                    'sms_count': data['send_date__count']
                }
            else:
                # Last 30 days option
                sms_dict[int(ctime.strftime("%Y%m%d"))] = {
                    'sms_count': data['send_date__count']
                }

        dateList = date_range(mintime, maxtime, q=search_type)

        i = 0
        total_record = {}
        for date in dateList:
            inttime = int(date.strftime("%Y%m%d"))
            # last 7 days | yesterday | last 24 hrs
            if (int(search_type) == SEARCH_TYPE.B_Last_7_days
                    or int(search_type) == SEARCH_TYPE.C_Yesterday
                    or int(search_type) == SEARCH_TYPE.D_Last_24_hours):

                for option in range(0, 24):
                    day_time = int(str(inttime) + str(option).zfill(2))

                    graph_day = datetime(int(date.strftime("%Y")),
                                         int(date.strftime("%m")),
                                         int(date.strftime("%d")),
                                         int(str(option).zfill(2))).replace(tzinfo=utc)

                    dt = int(1000 * time.mktime(graph_day.timetuple()))
                    total_record[dt] = {'sms_count': 0}

                    if day_time in sms_dict.keys():
                        total_record[dt]['sms_count'] += sms_dict[day_time]['sms_count']

            # last 12 hrs | last 6 hrs | last 1 hrs
            elif (int(search_type) == SEARCH_TYPE.E_Last_12_hours
                  or int(search_type) == SEARCH_TYPE.F_Last_6_hours
                  or int(search_type) == SEARCH_TYPE.G_Last_hour):

                for hour in range(0, 24):
                    for minute in range(0, 60):
                        hr_time = int(str(inttime) + str(hour).zfill(2) + str(minute).zfill(2))

                        graph_day = datetime(int(date.strftime("%Y")),
                                             int(date.strftime("%m")),
                                             int(date.strftime("%d")),
                                             int(str(hour).zfill(2)),
                                             int(str(minute).zfill(2))).replace(tzinfo=utc)

                        dt = int(1000 * time.mktime(graph_day.timetuple()))
                        total_record[dt] = {'sms_count': 0}

                        if hr_time in sms_dict_with_min.keys():
                            total_record[dt]['sms_count'] += sms_dict_with_min[hr_time]['sms_count']

            else:
                # Last 30 days option
                graph_day = datetime(int(date.strftime("%Y")),
                                     int(date.strftime("%m")),
                                     int(date.strftime("%d"))).replace(tzinfo=utc)
                dt = int(1000 * time.mktime(graph_day.timetuple()))
                total_record[dt] = {'sms_count': 0}
                if inttime in sms_dict.keys():
                    total_record[dt]['sms_count'] += sms_dict[inttime]['sms_count']

    # sorting on date col
    total_record = total_record.items()
    total_record = sorted(total_record, key=lambda k: k[0])

    # lineWithFocusChart
    final_charttype = "lineWithFocusChart"
    xdata = []
    ydata = []
    for i in total_record:
        xdata.append(i[0])
        ydata.append(i[1]['sms_count'])

    tooltip_date = "%d %b %y %H:%M %p"
    extra_serie1 = {
        "tooltip": {"y_start": "", "y_end": " SMS"},
        "date_format": tooltip_date
    }

    final_chartdata = {
        'x': xdata,
        'name1': 'SMS', 'y1': ydata, 'extra1': extra_serie1,
    }

    # Contacts which are successfully messaged for running sms campaign
    reached_contact = 0
    if sms_campaign_id_list:
        now = datetime.utcnow().replace(tzinfo=utc)
        start_date = datetime(now.year, now.month, now.day, 0, 0, 0, 0).replace(tzinfo=utc)
        end_date = datetime(now.year, now.month, now.day, 23, 59, 59, 999999).replace(tzinfo=utc)
        sms_campaign_subscriber = SMSCampaignSubscriber.objects.filter(
            sms_campaign_id__in=sms_campaign_id_list,
            status=SMS_SUBSCRIBER_STATUS.COMPLETE,
            updated_date__range=(start_date, end_date)).count()
        reached_contact += sms_campaign_subscriber

    # PieChart
    sms_analytic_charttype = "pieChart"
    xdata = []
    ydata = []
    sms_analytic_chartdata = {'x': xdata, 'y1': ydata}

    if total_sms_count != 0:
        for i in SMS_MESSAGE_STATUS:
            xdata.append(i[0].upper())

        # Y-axis order depend upon SMS_MESSAGE_STATUS
        # 'UNSENT', 'SENT', 'DELIVERED', 'FAILED', 'NO_ROUTE', 'UNAUTHORIZED'
        ydata = [
            percentage(total_unsent, total_sms_count),
            percentage(total_sent, total_sms_count),
            percentage(total_delivered, total_sms_count),
            percentage(total_failed, total_sms_count),
            percentage(total_no_route, total_sms_count),
            percentage(total_unauthorized, total_sms_count),
        ]

        color_list = [
            COLOR_SMS_DISPOSITION['UNSENT'],
            COLOR_SMS_DISPOSITION['SENT'],
            COLOR_SMS_DISPOSITION['DELIVERED'],
            COLOR_SMS_DISPOSITION['FAILED'],
            COLOR_SMS_DISPOSITION['NO_ROUTE'],
            COLOR_SMS_DISPOSITION['UNAUTHORIZED'],
        ]
        extra_serie = {
            "tooltip": {"y_start": "", "y_end": " %"},
            "color_list": color_list
        }
        kwargs1 = {}
        kwargs1['resize'] = True
        sms_analytic_chartdata = {
            'x': xdata, 'y1': ydata, 'extra1': extra_serie,
            'kwargs1': kwargs1,
        }

    data = {
        'form': form,
        'SEARCH_TYPE': SEARCH_TYPE,
        'pb_active_contact_count': pb_active_contact_count,
        'reached_contact': reached_contact,
        'total_record': total_record,
        'select_graph_for': select_graph_for,
        'total_sms_count': total_sms_count,
        'total_unsent': total_unsent,
        'total_sent': total_sent,
        'total_delivered': total_delivered,
        'total_failed': total_failed,
        'total_no_route': total_no_route,
        'total_unauthorized': total_unauthorized,
        'unsent_color': COLOR_SMS_DISPOSITION['UNSENT'],
        'sent_color': COLOR_SMS_DISPOSITION['SENT'],
        'delivered_color': COLOR_SMS_DISPOSITION['DELIVERED'],
        'failed_color': COLOR_SMS_DISPOSITION['FAILED'],
        'no_route_color': COLOR_SMS_DISPOSITION['NO_ROUTE'],
        'unauthorized_color': COLOR_SMS_DISPOSITION['UNAUTHORIZED'],
        'final_chartcontainer': 'lineplusbarwithfocuschart_container',
        'final_chartdata': final_chartdata,
        'final_charttype': final_charttype,
        'final_extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %Y',
            'tag_script_js': True,
            'jquery_on_ready': False,
        },
        'sms_analytic_chartcontainer': 'piechart_container',
        'sms_analytic_charttype': sms_analytic_charttype,
        'sms_analytic_chartdata': sms_analytic_chartdata,
        'sms_analytic_extra': {
            'x_is_date': False,
            'x_axis_format': '',
            'tag_script_js': True,
            'jquery_on_ready': False,
        },
    }
    if on_index == 'yes':
        return data
    return render_to_response('mod_sms/sms_dashboard.html', data, context_instance=RequestContext(request))

Example 168

Project: virtmgr
Source File: views.py
View license
def snapshot(request, host_id, vname):

	if not request.user.is_authenticated():
		return HttpResponseRedirect('/')

	kvm_host = Host.objects.get(user=request.user.id, id=host_id)

	def add_error(msg, type_err):
		error_msg = Log(host_id=host_id, 
			            type=type_err, 
			            message=msg, 
			            user_id=request.user.id
			            )
		error_msg.save()

	def get_vms():
		try:
			vname = {}
			for id in conn.listDomainsID():
				id = int(id)
				dom = conn.lookupByID(id)
				vname[dom.name()] = dom.info()[0]
			for id in conn.listDefinedDomains():
				dom = conn.lookupByName(id)
				vname[dom.name()] = dom.info()[0]
			return vname
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def get_vm_snapshots():
		try:
			vname = {}
			for id in conn.listDomainsID():
				id = int(id)
				dom = conn.lookupByID(id)
				if dom.snapshotNum(0) != 0:
					vname[dom.name()] = dom.info()[0]
			for id in conn.listDefinedDomains():
				dom = conn.lookupByName(id)
				if dom.snapshotNum(0) != 0:
					vname[dom.name()] = dom.info()[0]
			return vname
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def vm_conn():
	   	try:
			flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
	  		auth = [flags, creds, None]
			uri = 'qemu+tcp://' + kvm_host.ipaddr + '/system'
		   	conn = libvirt.openAuth(uri, auth, 0)
		   	return conn
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	if not kvm_host.login or not kvm_host.passwd:
		def creds(credentials, user_data):
			for credential in credentials:
				if credential[0] == libvirt.VIR_CRED_AUTHNAME:
					credential[4] = request.session['login_kvm']
					if len(credential[4]) == 0:
						credential[4] = credential[3]
				elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
					credential[4] = request.session['passwd_kvm']
				else:
					return -1
			return 0
	else:
		def creds(credentials, user_data):
			for credential in credentials:
				if credential[0] == libvirt.VIR_CRED_AUTHNAME:
					credential[4] = kvm_host.login
					if len(credential[4]) == 0:
						credential[4] = credential[3]
				elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
					credential[4] = kvm_host.passwd
				else:
					return -1
			return 0

	def get_dom(vname):
		try:
			dom = conn.lookupByName(vname)
			return dom
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def get_snapshots():
		try:
			snapshots = {}
			all_snapshot = dom.snapshotListNames(0)
			for snapshot in all_snapshot:
				snapshots[snapshot] = (datetime.fromtimestamp(int(snapshot)), dom.info()[0])
			return snapshots
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def del_snapshot(name_snap):
		try:
			snap = dom.snapshotLookupByName(name_snap,0)
			snap.delete(0)
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def revert_snapshot(name_snap):
		try:
			snap = dom.snapshotLookupByName(name_snap,0)
			dom.revertToSnapshot(snap,0)
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	conn = vm_conn()
	all_vm_snapshots = get_vm_snapshots()
	dom = get_dom(vname)
	vm_snapshot = get_snapshots()
	all_vm = get_vms()

	if not vm_snapshot:
		return HttpResponseRedirect('/snapshot/%s/' % (host_id))

	if request.method == 'POST':
		if request.POST.get('delete',''):
			name = request.POST.get('name','')
			msg = _('Delete snapshot VM: ')
			msg = msg + vname + ' => ' + name
			add_error(msg,'user')
			del_snapshot(name)
			return HttpResponseRedirect('/snapshot/%s/%s/' % (host_id, vname))
		if request.POST.get('revert',''):
			name = request.POST.get('name','')
			msg = _('Revert snapshot VM: ')
			msg = msg + vname + ' => ' + name
			add_error(msg,'user')
        	revert_snapshot(name)
        	message = _('Successful revert snapshot: ')
        	message = message + name

	conn.close()

	return render_to_response('snapshot.html', locals())

Example 169

Project: snipt-old
Source File: views.py
View license
def user_page(request, user, slug, feed=False):
    
    # Set disable message to false.
    # request.session['disable_message'] = False
    
    # If the user has requested a tag listing page, handle accordingly, otherwise serve latest snipts.
    if request.user.username != user:
        mine = False
        try:
            context_user = User.objects.get(username=user)
            if context_user.username == 'public':
                public = True
            else:
                public = False
        except:
            raise Http404()
    else:
        mine = True
        context_user = request.user
    if slug is not None:
        slug = slug.replace('tag/','')

        """
        Attempt to retrieve the tag for this particular slug.  In the event that there is no tag
        associated with this slug, set tag to 'None'.
        """
        try:
            tag = Tag.objects.get(name = slug)
        except:
            tag = None

        # If the tag exists, retrieve the snipts that this user has tagged with this particular tag.
        if tag is not None:
            if mine:
                snipts = TaggedItem.objects.get_by_model(Snippet.objects.filter(user=context_user.id).order_by('-created'), tag)
                
                from snipt.favsnipt.models import FavSnipt
                favsnipts = FavSnipt.objects.filter(user=context_user.id)
                favrd = []
                for fs in favsnipts:
                    fs.snipt.favrd = True
                    fs.snipt.created = fs.created
                    if str(tag) in fs.snipt.tags:
                        favrd.append(fs.snipt)

                from operator import attrgetter
                from itertools import chain
                snipts = sorted(
                    chain(snipts, favrd),
                    key=attrgetter('created'), reverse=True)
                
            elif not public:
                snipts = TaggedItem.objects.get_by_model(Snippet.objects.filter(user=context_user.id, public='1').order_by('-created'), tag)
            else:
                snipts = TaggedItem.objects.get_by_model(Snippet.objects.filter(public='1').order_by('-created'), tag)

        # If the tag does not exist, raise 404.
        else:
            raise Http404()

        # If the tag exists, but the user has no snipts for this particular tag, raise 404.
        if len(snipts) == 0:
            raise Http404()

    # If the user is at the homepage (no tag specified).
    else:

        # Retrieve latest 20 snipts for user.
        if mine:
            snipts = Snippet.objects.filter(user=context_user.id).order_by('-created')
            
            from snipt.favsnipt.models import FavSnipt
            favsnipts = FavSnipt.objects.filter(user=context_user.id)
            favrd = []
            for fs in favsnipts:
                fs.snipt.favrd = True
                fs.snipt.created = fs.created
                favrd.append(fs.snipt)
            
            from operator import attrgetter
            from itertools import chain
            snipts = sorted(
                chain(snipts, favrd),
                key=attrgetter('created'), reverse=True)
            
        elif not public:
            snipts = Snippet.objects.filter(user=context_user.id, public='1').order_by('-created')
        else:
            snipts = Snippet.objects.filter(public='1').order_by('-created')[:100]

    # Compile the list of tags that this user has used.
    if mine:
        user_tags_list = Tag.objects.usage_for_queryset(Snippet.objects.filter(user=context_user.id).order_by('-created'), counts=True)
    elif not public:
        user_tags_list = Tag.objects.usage_for_queryset(Snippet.objects.filter(user=context_user.id, public='1').order_by('-created'), counts=True)
    else:
        user_tags_list = Tag.objects.usage_for_queryset(Snippet.objects.filter(public='1'), counts=True)
        if not DEBUG:
            user_tags_list.sort(key=lambda x: x.count, reverse=True)
        user_tags_list = user_tags_list[:40]
    
    for usertag in user_tags_list:
        usertag.slug = str(usertag)

    disable_wrap = request.session.get('disable_wrap')
    disable_message = request.session.get('disable_message')

    if mine:
        total_count = Snippet.objects.filter(user=context_user.id).count()
    elif not public:
        total_count = Snippet.objects.filter(user=context_user.id, public='1').count()
    else:
        total_count = Snippet.objects.filter(public='1').count()

    if total_count > 0:
        # Get the last lexer used so we can auto-select that one.
        if mine:
            last_lexer = Snippet.objects.filter(user=context_user.id).order_by('-created')[0].lexer
            
    snipts_count = len(snipts)
    
    # Send a modified version of the request path so we may compare it to the list of tag slugs (to identify current page).
    if mine:
        request_tag = request.path.replace('/' + request.user.username + '/tag/','')
    else:
        request_tag = request.path.replace('/' + context_user.username + '/tag/','')

    if feed:
        try:
            snipts = TaggedItem.objects.get_by_model(Snippet.objects.filter(user=context_user.id, public='1').order_by('-created'), tag)
        except:
            snipts = Snippet.objects.filter(user=context_user.id, public='1').order_by('-created')
        real_path = request.path.replace('/feed', '')
        if '/all' not in request.path:
            snipts = snipts.filter()[:20]
        return render_to_response('feed.xml', locals(), context_instance=RequestContext(request), mimetype="application/rss+xml")
    else:
        return render_to_response('home_user.html', locals(), context_instance=RequestContext(request))

Example 170

Project: edx-platform
Source File: views.py
View license
@require_GET
@login_required
@use_bulk_ops
def single_thread(request, course_key, discussion_id, thread_id):
    """
    Renders a response to display a single discussion thread.  This could either be a page refresh
    after navigating to a single thread, a direct link to a single thread, or an AJAX call from the
    discussions UI loading the responses/comments for a single thread.

    Depending on the HTTP headers, we'll adjust our response accordingly.
    """
    nr_transaction = newrelic.agent.current_transaction()

    course = get_course_with_access(request.user, 'load', course_key, check_if_enrolled=True)
    course_settings = make_course_settings(course, request.user)
    cc_user = cc.User.from_django_user(request.user)
    user_info = cc_user.to_dict()
    is_moderator = has_permission(request.user, "see_all_cohorts", course_key)
    is_staff = has_permission(request.user, 'openclose_thread', course.id)

    try:
        thread = cc.Thread.find(thread_id).retrieve(
            with_responses=request.is_ajax(),
            recursive=request.is_ajax(),
            user_id=request.user.id,
            response_skip=request.GET.get("resp_skip"),
            response_limit=request.GET.get("resp_limit")
        )
    except cc.utils.CommentClientRequestError as error:
        if error.status_code == 404:
            raise Http404
        raise

    # Verify that the student has access to this thread if belongs to a course discussion module
    thread_context = getattr(thread, "context", "course")
    if thread_context == "course" and not utils.discussion_category_id_access(course, request.user, discussion_id):
        raise Http404

    # verify that the thread belongs to the requesting student's cohort
    if is_commentable_cohorted(course_key, discussion_id) and not is_moderator:
        user_group_id = get_cohort_id(request.user, course_key)
        if getattr(thread, "group_id", None) is not None and user_group_id != thread.group_id:
            raise Http404

    if request.is_ajax():
        with newrelic.agent.FunctionTrace(nr_transaction, "get_annotated_content_infos"):
            annotated_content_info = utils.get_annotated_content_infos(
                course_key,
                thread,
                request.user,
                user_info=user_info
            )

        content = utils.prepare_content(thread.to_dict(), course_key, is_staff)
        with newrelic.agent.FunctionTrace(nr_transaction, "add_courseware_context"):
            add_courseware_context([content], course, request.user)

        return utils.JsonResponse({
            'content': content,
            'annotated_content_info': annotated_content_info,
        })
    else:
        # Since we're in page render mode, and the discussions UI will request the thread list itself,
        # we need only return the thread information for this one.
        threads = [thread.to_dict()]

        with newrelic.agent.FunctionTrace(nr_transaction, "add_courseware_context"):
            add_courseware_context(threads, course, request.user)

        for thread in threads:
            # patch for backward compatibility with comments service
            if "pinned" not in thread:
                thread["pinned"] = False

        threads = [utils.prepare_content(thread, course_key, is_staff) for thread in threads]

        with newrelic.agent.FunctionTrace(nr_transaction, "get_metadata_for_threads"):
            annotated_content_info = utils.get_metadata_for_threads(course_key, threads, request.user, user_info)

        with newrelic.agent.FunctionTrace(nr_transaction, "get_cohort_info"):
            user_cohort = get_cohort_id(request.user, course_key)

        context = {
            'discussion_id': discussion_id,
            'csrf': csrf(request)['csrf_token'],
            'init': '',   # TODO: What is this?
            'user_info': user_info,
            'can_create_comment': has_permission(request.user, "create_comment", course.id),
            'can_create_subcomment': has_permission(request.user, "create_sub_comment", course.id),
            'can_create_thread': has_permission(request.user, "create_thread", course.id),
            'annotated_content_info': annotated_content_info,
            'course': course,
            #'recent_active_threads': recent_active_threads,
            'course_id': course.id.to_deprecated_string(),   # TODO: Why pass both course and course.id to template?
            'thread_id': thread_id,
            'threads': threads,
            'roles': utils.get_role_ids(course_key),
            'is_moderator': is_moderator,
            'thread_pages': 1,
            'is_course_cohorted': is_course_cohorted(course_key),
            'flag_moderator': bool(
                has_permission(request.user, 'openclose_thread', course.id) or
                has_access(request.user, 'staff', course)
            ),
            'cohorts': course_settings["cohorts"],
            'user_cohort': user_cohort,
            'sort_preference': cc_user.default_sort_key,
            'category_map': course_settings["category_map"],
            'course_settings': course_settings,
            'disable_courseware_js': True,
            'uses_pattern_library': True,
        }
        return render_to_response('discussion/discussion_board.html', context)

Example 171

Project: Nitrate
Source File: ajax.py
View license
def tag(request, template_name="management/get_tag.html"):
    """Get tags for test plan or test case"""

    class Objects(object):
        __all__ = ['plan', 'case', 'run']

        def __init__(self, request, template_name):
            self.request = request
            self.template_name = template_name
            for o in self.__all__:
                if request.REQUEST.get(o):
                    self.object = o
                    self.object_pks = request.REQUEST.getlist(o)
                    break

        def get(self):
            func = getattr(self, self.object)
            return func()

        def plan(self):
            return self.template_name, TestPlan.objects.filter(
                pk__in=self.object_pks)

        def case(self):
            from tcms.testcases.views import get_selected_testcases

            return self.template_name, get_selected_testcases(self.request)

        def run(self):
            self.template_name = 'run/get_tag.html'
            return self.template_name, TestRun.objects.filter(
                pk__in=self.object_pks)

    class TagActions(object):
        __all__ = ['add', 'remove']

        def __init__(self, obj, tag):
            self.obj = obj
            self.tag = TestTag.string_to_list(tag)
            self.request = request

        def add(self):
            for tag_str in self.tag:
                try:
                    tag, c = TestTag.objects.get_or_create(name=tag_str)
                    for o in self.obj:
                        o.add_tag(tag)
                except:
                    return "Error when adding %s" % self.tag

            return True, self.obj

        def remove(self):
            self.obj = self.obj.filter(tag__name__in=self.tag).distinct()

            if not self.obj:
                return "Tags does not exist in current selected plan."

            else:
                for tag_str in self.tag:
                    try:
                        tag = TestTag.objects.filter(name=tag_str)[0]
                    except IndexError:
                        return "Tag %s does not exist in current selected " \
                               "plan." % tag_str

                    for o in self.obj:
                        try:
                            o.remove_tag(tag)
                        except:
                            return "Remove tag %s error." % tag
                return True, self.obj

    objects = Objects(request, template_name)
    template_name, obj = objects.get()

    q_tag = request.REQUEST.get('tags')
    q_action = request.REQUEST.get('a')
    if q_action:
        tag_actions = TagActions(obj=obj, tag=q_tag)
        func = getattr(tag_actions, q_action)
        response = func()
        if not response[0]:
            return HttpResponse(
                simplejson.dumps({'response': response, 'rc': 1}))

    del q_tag, q_action

    # Response to batch operations
    if request.REQUEST.get('t') == 'json':
        if request.REQUEST.get('f') == 'serialized':
            return HttpResponse(
                # FIXME: this line of code depends on the existence of `a`
                # argument in query string. So, if a does not appear in the
                # query string, error will happen here
                serializers.serialize(request.REQUEST['t'], response[1])
            )

        return HttpResponse(simplejson.dumps({'response': 'ok'}))

    # Response the single operation
    if len(obj) == 1:
        tags = obj[0].tag.all()
        tags = tags.extra(select={
            'num_plans':
                'SELECT COUNT(*) FROM test_plan_tags '
                'WHERE test_tags.tag_id = test_plan_tags.tag_id',
            'num_cases':
                'SELECT COUNT(*) FROM test_case_tags '
                'WHERE test_tags.tag_id = test_case_tags.tag_id',
            'num_runs':
                'SELECT COUNT(*) FROM test_run_tags '
                'WHERE test_tags.tag_id = test_run_tags.tag_id',
        })

        context_data = {
            'tags': tags,
            'object': obj[0],
        }
        return render_to_response(template_name, context_data,
                                  context_instance=RequestContext(request))
    return HttpResponse('')

Example 172

Project: foodnetwork
Source File: views.py
View license
@login_required
def planning_table(request, member_id, list_type, from_date, to_date):
    try:
        member = Party.objects.get(pk=member_id)
    except Party.DoesNotExist:
        raise Http404
    role = "producer"
    plan_type = "Production"
    if member.is_customer():
        role = "consumer"
        plan_type = "Consumption"

    try:
        from_date = datetime.datetime(*time.strptime(from_date, '%Y_%m_%d')[0:5]).date()
        to_date = datetime.datetime(*time.strptime(to_date, '%Y_%m_%d')[0:5]).date()
    except ValueError:
            raise Http404
    # force from_date to Monday, to_date to Sunday
    from_date = from_date - datetime.timedelta(days=datetime.date.weekday(from_date))
    to_date = to_date - datetime.timedelta(days=datetime.date.weekday(to_date)+1)
    to_date = to_date + datetime.timedelta(days=7)
    products = None
    if list_type == "M":
        if role == "consumer":
            products = CustomerProduct.objects.filter(customer=member, planned=True)
        else:
            products = ProducerProduct.objects.filter(producer=member, planned=True)
    if not products:
        products = Product.objects.filter(plannable=True)
        list_type = "A"
    plan_table = plan_weeks(member, products, from_date, to_date)
    forms = create_weekly_plan_forms(plan_table.rows, data=request.POST or None)
    if request.method == "POST":
        for row in forms:
            if row.formset.is_valid():
                for form in row.formset.forms:
                    data = form.cleaned_data
                    qty = data['quantity']
                    plan_id = data['plan_id']
                    from_dt = data['from_date']
                    to_dt = data['to_date']
                    product_id = data['product_id']
                    plan = None
                    if plan_id:
                        # what if plan was changed by prev cell?
                        plan = ProductPlan.objects.get(id=plan_id)
                        if plan.to_date < from_dt or plan.from_date > to_dt:
                            plan = None
                    if qty:
                        if plan:
                            if not qty == plan.quantity:
                                if plan.from_date >= from_dt and plan.to_date <= to_dt:
                                    plan.quantity = qty
                                    plan.save()
                                else:
                                    if plan.from_date < from_dt:
                                        new_to_dt = from_dt - datetime.timedelta(days=1)
                                        earlier_plan = ProductPlan(
                                            member=plan.member,
                                            product=plan.product,
                                            quantity=plan.quantity,
                                            from_date=plan.from_date,
                                            to_date=new_to_dt,
                                            role=plan.role,
                                            inventoried=plan.inventoried,
                                            distributor=plan.distributor,
                                        )
                                        earlier_plan.save()
                                    if plan.to_date > to_dt:
                                        new_plan = ProductPlan(
                                            member=plan.member,
                                            product=plan.product,
                                            quantity=qty,
                                            from_date=from_dt,
                                            to_date=to_dt,
                                            role=plan.role,
                                            inventoried=plan.inventoried,
                                            distributor=plan.distributor,
                                        )
                                        new_plan.save()
                                        plan.from_date = to_dt + datetime.timedelta(days=1)
                                        plan.save()
                                    else:
                                        plan.from_date=from_dt
                                        plan.quantity=qty
                                        plan.save()      
                        else:
                            product = Product.objects.get(id=product_id)
                            new_plan = ProductPlan(
                                member=member,
                                product=product,
                                quantity=qty,
                                from_date=from_dt,
                                to_date=to_dt,
                                role=role,
                            )
                            new_plan.save()
                            if role == "producer":
                                listed_product, created = ProducerProduct.objects.get_or_create(
                                    product=product, producer=member)
                            #elif role == "consumer":
                            #    listed_product, created = CustomerProduct.objects.get_or_create(
                            #        product=product, customer=member)

                    else:
                        if plan:
                            if plan.from_date >= from_dt and plan.to_date <= to_dt:
                                plan.delete()
                            else:
                                if plan.to_date > to_dt:
                                    early_from_dt = plan.from_date              
                                    if plan.from_date < from_dt:
                                        early_to_dt = from_dt - datetime.timedelta(days=1)
                                        earlier_plan = ProductPlan(
                                            member=plan.member,
                                            product=plan.product,
                                            quantity=plan.quantity,
                                            from_date=early_from_dt,
                                            to_date=early_to_dt,
                                            role=plan.role,
                                            inventoried=plan.inventoried,
                                            distributor=plan.distributor,
                                         )
                                        earlier_plan.save()
                                    plan.from_date = to_dt + datetime.timedelta(days=1)
                                    plan.save()
                                else:
                                    plan.to_date= from_dt - datetime.timedelta(days=1)
                                    plan.save()
        from_date = from_date.strftime('%Y_%m_%d')
        to_date = to_date.strftime('%Y_%m_%d')
        return HttpResponseRedirect('/%s/%s/%s/%s/'
                    % ('producer/producerplans', from_date, to_date, member_id))
    return render_to_response('distribution/planning_table.html', 
        {
            'from_date': from_date,
            'to_date': to_date,
            'plan_table': plan_table,
            'forms': forms,
            'plan_type': plan_type,
            'member': member,
            'list_type': list_type,
            'tabnav': "producer/producer_tabnav.html",
        }, context_instance=RequestContext(request))

Example 173

Project: Nitrate
Source File: views.py
View license
def environment_properties(request, template_name='environment/property.html'):
    """
    Edit environemnt properties and values belong to
    """

    # Initial the ajax response
    ajax_response = {'rc': 0, 'response': 'ok'}
    message = ''

    has_perm = request.user.has_perm
    user_action = request.REQUEST.get('action')

    # Actions of create properties
    if user_action == 'add':
        if not has_perm('management.add_tcmsenvproperty'):
            ajax_response['response'] = 'Permission denied'
            ajax_response['rc'] = 1
            return HttpResponse(json_dumps(ajax_response))

        property_name = request.REQUEST.get('name')

        if not property_name:
            ajax_response['response'] = 'Property name is required'
            ajax_response['rc'] = 1
            return HttpResponse(json_dumps(ajax_response))

        try:
            new_property = TCMSEnvProperty.objects.create(name=property_name)
            ajax_response['id'] = new_property.id
            ajax_response['name'] = new_property.name

        except IntegrityError, error:
            if error[1].startswith('Duplicate'):
                resp_msg = 'Environment proprerty named \'%s\' already ' \
                    'exists, please select another name.' % property_name
            else:
                resp_msg = error[1]

            ajax_response['rc'] = 1
            ajax_response['response'] = resp_msg
            return HttpResponse(json_dumps(ajax_response))

        return HttpResponse(json_dumps(ajax_response))

    # Actions of edit a exist properties
    if user_action == 'edit':
        if not has_perm('management.change_tcmsenvproperty'):
            ajax_response['response'] = 'Permission denied'
            ajax_response['rc'] = 1
            return HttpResponse(json_dumps(ajax_response))

        if not request.REQUEST.get('id'):
            ajax_response['response'] = 'ID is required'
            ajax_response['rc'] = 1
            return HttpResponse(json_dumps(ajax_response))

        try:
            env_property = TCMSEnvProperty.objects.get(
                id=request.REQUEST['id'])
            env_property.name = request.REQUEST.get('name', env_property.name)
            try:
                env_property.save()
            except IntegrityError, error:
                ajax_response['response'] = error[1]
                ajax_response['rc'] = 1
                return HttpResponse(json_dumps(ajax_response))

        except TCMSEnvProperty.DoesNotExist, error:
            ajax_response['response'] = error[1]
            ajax_response['rc'] = 1

        return HttpResponse(json_dumps(ajax_response))

    # Actions of remove properties
    if user_action == 'del':
        if not has_perm('management.delete_tcmsenvproperty'):
            message = 'Permission denied'

        property_ids = request.REQUEST.getlist('id')

        if has_perm('management.delete_tcmsenvproperty') and property_ids:
            try:
                filter = TCMSEnvGroupPropertyMap.objects.filter

                env_group_property_map = filter(property__id__in=property_ids)
                env_group_property_map and env_group_property_map.delete()

                env_group_value_map = filter(property__id__in=property_ids)
                env_group_value_map and env_group_value_map.delete()
            except:
                pass

            try:
                env_properties = TCMSEnvProperty.objects.filter(
                    id__in=property_ids)
                property_values = '\', \''.join(
                    env_properties.values_list('name', flat=True))
                message = 'Remove test properties %s successfully.' % \
                    property_values
                env_properties.delete()
            except TCMSEnvProperty.DoesNotExist as error:
                message = error[1]

    # Actions of remove properties
    if user_action == 'modify':
        if not has_perm('management.change_tcmsenvproperty'):
            message = 'Permission denied'

        property_ids = request.REQUEST.getlist('id')

        if has_perm('management.change_tcmsenvproperty') and property_ids:
            try:
                env_properties = TCMSEnvProperty.objects.filter(
                    id__in=property_ids)

                if request.REQUEST.get('status') in ['0', '1']:
                    for env_property in env_properties:
                        env_property.is_active = int(request.REQUEST['status'])
                        env_property.save()

                    property_values = '\', \''.join(
                        env_properties.values_list('name', flat=True))
                    message = 'Modify test properties status \'%s\' ' \
                              'successfully.' % property_values
                else:
                    message = 'Argument illegel'

            except TCMSEnvProperty.DoesNotExist as error:
                message = error[1]

            try:
                filter = TCMSEnvGroupPropertyMap.objects.filter

                env_group_property_map = filter(property__id__in=property_ids)
                env_group_property_map and env_group_property_map.delete()

                env_group_value_map = filter(property__id__in=property_ids)
                env_group_value_map and env_group_value_map.delete()
            except:
                pass

    if request.is_ajax():
        ajax_response['rc'] = 1
        ajax_response['response'] = 'Unknown action'
        return HttpResponse(json_dumps(ajax_response))

    context_data = {
        'message': message,
        'properties': TCMSEnvProperty.objects.all().order_by('-is_active')
    }
    return render_to_response(template_name, context_data,
                              context_instance=RequestContext(request))

Example 174

Project: gpgvote
Source File: views.py
View license
def poll(request, action, poll_id):
  if not request.user.is_authenticated():
    return HttpResponseRedirect('/')
  else:
    logged_in = True

  choices_error = ''
  dates_error = ''
  num_of_choices_error = ''
  allowed_voters_error = ''
  success = ''
  poll_data = {}
  poll_choices = []
  
  if action == 'edit':
    try:
      poll = Poll.objects.get(pk = poll_id)
    except Poll.DoesNotExist:
      raise Http404
    # allow edit only for creator and only if the poll has not started yet
    if (request.user != poll.creator) or (poll.starts < datetime.datetime.now()):
      return HttpResponseRedirect('/')
    poll_data = {    'question': poll.question,
                  'min_choices': poll.min_choices,
                  'max_choices': poll.max_choices,
                  'starts_date': poll.starts.date(),
                  'starts_time': poll.starts.time(),
                    'ends_date': poll.ends.date(),
                    'ends_time': poll.ends.time()   }
    poll_choices = Choice.objects.filter(poll = poll).order_by('id')
                         
  # Clean PGPkey records to correct is_trusted field
  for key in PGPkey.objects.all():
    key.clean()
  
  # Get trusted users and create allowed voters choices
  trusted_users = User.objects.filter(pgpkey__is_trusted=True).order_by('pgpkey__name')
  allowed_voters = ()
  for user in trusted_users:
    allowed_voters = allowed_voters + ( (user.username, user.pgpkey.name + ' <' + user.username + '>' ), )
  
  if request.POST:
    # allow edit only if the poll has not started yet
    if (action == 'edit'):
      if (poll.starts < datetime.datetime.now()):
        return HttpResponseRedirect('/')
      
    form = PollForm(allowed_voters, request.POST, initial = poll_data)
    if form.is_valid():
      poll_choices = request.POST.getlist('choices')
      if len(poll_choices) < 2:
        choices_error = '<ul><li>You must add at least 2 choices</li></ul>'
      else:
	for choice in poll_choices:
	  if len(choice) > 255:
	    choices_error = '<ul><li>Each choice must be up to 255 characters in length</li></ul>'
      
      (dates_error, starts_datetime, ends_datetime) = dates_check(
                                                        form.cleaned_data['starts_date'],
                                                        form.cleaned_data['starts_time'], 
                                                        form.cleaned_data['ends_date'],
                                                        form.cleaned_data['ends_time'] )
      num_of_choices_error = num_of_choices_check(len(poll_choices), 
                                                  form.cleaned_data['min_choices'], 
                                                  form.cleaned_data['max_choices'])                                                  
      if len(form.cleaned_data['allowed_voters']) < 2:
	allowed_voters_error = '<ul><li>You must select at least 2 voters</li></ul>'
      
      if not (choices_error or dates_error or num_of_choices_error or allowed_voters_error):
	if action == 'create':
	  poll = Poll(
	           creator = request.user,  
	           question = form.cleaned_data['question'],
	           min_choices = form.cleaned_data['min_choices'],
	           max_choices = form.cleaned_data['max_choices'],
	           allowed_voters = '',
	           who_voted = '',
	           starts = starts_datetime,
	           ends = ends_datetime )
	else:
	  poll.question = form.cleaned_data['question']
	  poll.min_choices = form.cleaned_data['min_choices']
	  poll.max_choices = form.cleaned_data['max_choices']
	  poll.allowed_voters = ''
          poll.starts = starts_datetime
	  poll.ends = ends_datetime
        
	for voter in form.cleaned_data['allowed_voters']:
	  poll.add_voter(voter, To = 'allowed_voters')
        poll.save()
        
        # Delete old choices before adding their new versions
        if action == 'edit':
          Choice.objects.filter(poll = poll).delete()
        for choice in poll_choices:
	  choice = Choice(poll = poll, choice = choice)
	  choice.save()

        if action == 'create':
	  success = 'You have successfully created a new poll'
	else:
	  success = 'You have successfully edited the poll'
  else:
    form = PollForm(allowed_voters, initial = poll_data)
  
  if action == 'edit':
    poll_id = poll.id
  else:
    poll_id = ''
    
  return render_to_response('poll.html', 
         {                 'form': form,
                         'action': action,
                        'poll_id': poll_id,
                        'choices': poll_choices,
                  'choices_error': choices_error,
                    'dates_error': dates_error,
           'num_of_choices_error': num_of_choices_error,
           'allowed_voters_error': allowed_voters_error,
                        'success': success,
                           'user': request.user.username,
                      'logged_in': logged_in }, context_instance = RequestContext(request))

Example 175

Project: Open-Knesset
Source File: views.py
View license
def main(request):
    """
    Note on annotations:
     Old:
        Return annotations by concatenating Annotation last 10 and Comment last
        10, adding all related comments (comments on same item that are older).
        annotations_old = get_annotations(
            annotations=list(Annotation.objects.all().order_by('-timestamp')[:10]),
            comments=Comment.objects.all().order_by('-submit_date')[:10])
     New:
        Return annotations by Action filtered to include only:
         annotation-added (to meeting), ignore annotated (by user)
         comment-added
    """
    #context = cache.get('main_page_context')
    #if not context:
    #    context = {
    #        'title': _('Home'),
    #        'hide_crumbs': True,
    #    }
    #    actions = list(main_actions()[:10])
    #
    #    annotations = get_annotations(
    #        annotations=[a.target for a in actions if a.verb != 'comment-added'],
    #        comments=[x.target for x in actions if x.verb == 'comment-added'])
    #    context['annotations'] = annotations
    #    b = get_debated_bills()
    #    if b:
    #        context['bill'] = get_debated_bills()[0]
    #    else:
    #        context['bill'] = None
    #    public_agenda_ids = Agenda.objects.filter(is_public=True
    #                                             ).values_list('id',flat=True)
    #    if len(public_agenda_ids) > 0:
    #        context['agenda_id'] = random.choice(public_agenda_ids)
    #    context['topics'] = Topic.objects.filter(status__in=PUBLIC_TOPIC_STATUS)\
    #                                     .order_by('-modified')\
    #                                     .select_related('creator')[:10]
    #    cache.set('main_page_context', context, 300) # 5 Minutes

    # did we post the TidbitSuggest form ?
    if request.method == 'POST':
        # only logged-in users can suggest
        if not request.user.is_authenticated:
            return HttpResponseForbidden()

        form = TidbitSuggestionForm(request.POST)
        if form.is_valid():
            form.save(request)

        return form.get_response()

    NUMOF_EVENTS = 8
    events = Event.objects.get_upcoming()

    # Reduce the number of sql queries, by prefetching the objects and setting
    # them on the objects
    upcoming = list(events[:NUMOF_EVENTS])

    generics = {}
    for item in upcoming:
        if item.which_pk:
            generics.setdefault(item.which_type_id, set()).add(item.which_pk)

    content_types = ContentType.objects.in_bulk(generics.keys())

    relations = {}
    for ct, fk_list in generics.items():
        ct_model = content_types[ct].model_class()
        relations[ct] = ct_model.objects.in_bulk(list(fk_list))

    for item in upcoming:
        if item.which_pk:
            setattr(item, '_which_object_cache',
                    relations[item.which_type_id].get(item.which_pk))

    context = {
        'title': _('Home'),
        'hide_crumbs': True,
        'is_index': True,
        'tidbits': Tidbit.active.all().order_by('?'),
        'suggestion_forms': {'tidbit': TidbitSuggestionForm()},
        'events': upcoming,
        'INITIAL_EVENTS': NUMOF_EVENTS,
        'events_more': events.count() > NUMOF_EVENTS,
    }
    template_name = '%s.%s%s' % ('main', settings.LANGUAGE_CODE, '.html')
    return render_to_response(template_name, context,
                              context_instance=RequestContext(request))

Example 176

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Example 177

Project: mloss
Source File: views.py
View license
def register(request, backend, success_url=None, form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register an account.

    The actual registration of the account will be delegated to the
    backend specified by the ``backend`` keyword argument (see below);
    it will be used as follows:

    1. The backend's ``registration_allowed()`` method will be called,
       passing the ``HttpRequest``, to determine whether registration
       of an account is to be allowed; if not, a redirect is issued to
       the view corresponding to the named URL pattern
       ``registration_disallowed``. To override this, see the list of
       optional arguments for this view (below).

    2. The form to use for account registration will be obtained by
       calling the backend's ``get_form_class()`` method, passing the
       ``HttpRequest``. To override this, see the list of optional
       arguments for this view (below).

    3. If valid, the form's ``cleaned_data`` will be passed (as
       keyword arguments, and along with the ``HttpRequest``) to the
       backend's ``register()`` method, which should return the new
       ``User`` object.

    4. Upon successful registration, the backend's
       ``post_registration_redirect()`` method will be called, passing
       the ``HttpRequest`` and the new ``User``, to determine the URL
       to redirect the user to. To override this, see the list of
       optional arguments for this view (below).
    
    **Required arguments**
    
    None.
    
    **Optional arguments**

    ``backend``
        The dotted Python import path to the backend class to use.

    ``disallowed_url``
        URL to redirect to if registration is not permitted for the
        current ``HttpRequest``. Must be a value which can legally be
        passed to ``django.shortcuts.redirect``. If not supplied, this
        will be whatever URL corresponds to the named URL pattern
        ``registration_disallowed``.
    
    ``form_class``
        The form class to use for registration. If not supplied, this
        will be retrieved from the registration backend.
    
    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``success_url``
        URL to redirect to after successful registration. Must be a
        value which can legally be passed to
        ``django.shortcuts.redirect``. If not supplied, this will be
        retrieved from the registration backend.
    
    ``template_name``
        A custom template to use. If not supplied, this will default
        to ``registration/registration_form.html``.
    
    **Context:**
    
    ``form``
        The registration form.
    
    Any extra variables supplied in the ``extra_context`` argument
    (see above).
    
    **Template:**
    
    registration/registration_form.html or ``template_name`` keyword
    argument.
    
    """
    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if form_class is None:
        form_class = backend.get_form_class(request)

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = backend.register(request, **form.cleaned_data)
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        form = form_class()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              {'form': form},
                              context_instance=context)

Example 178

Project: element43
Source File: views.py
View license
@login_required
def api_character(request, api_id, api_verification_code):

    """
    Validate key / ID combination. If it's valid, check security bitmask.
    """

    # Try to authenticate with supplied key / ID pair and fetch api key meta data.
    try:
        # Fetch info
        api = eveapi.EVEAPIConnection()
        auth = api.auth(keyID=api_id, vCode=api_verification_code)
        key_info = auth.account.APIKeyInfo()
    except:
        # Message and redirect
        messages.error(request, """Verification of your API key failed.
                                   Please follow the instructions on the right half of this page to generate a valid one.""")
        return HttpResponseRedirect(reverse('manage_api_keys'))

    if key_info.key.type == "Character" or key_info.key.type == "Account":

        # Minimum access mask
        min_access_mask = 8

        # attributes & implants
        implant = {}
        i_stats = {}
        attributes = ['memory', 'intelligence', 'perception', 'willpower', 'charisma']

        # Do a simple bitwise operation to determine if we have sufficient rights with this key.
        if not ((min_access_mask & key_info.key.accessMask) == min_access_mask):
            # Message and redirect
            messages.error(request, """The API key you supplied does not have sufficient rights.
                                       Please follow the instructions on the right half of this page to generate a valid one.""")
            return HttpResponseRedirect(reverse('manage_api_keys'))

        # Get characters associated with this key
        characters = auth.account.Characters().characters

        # If form is submitted, add characters to account
        if request.method == 'POST':
            post_characters = request.POST.getlist('characters')

            added_chars = False

            for char in characters:
                if str(char.characterID) in post_characters:
                    # Add key to DB if it does not exist
                    if not APIKey.objects.filter(keyid=api_id, vcode=api_verification_code):

                        # Handle keys which never expire
                        try:
                            key_expiration = datetime.datetime.fromtimestamp(key_info.key.expires)
                        except:
                            key_expiration = "9999-12-31 00:00:00"

                        key = APIKey(user=request.user,
                                     keyid=api_id,
                                     vcode=api_verification_code,
                                     expires=key_expiration,
                                     accessmask=key_info.key.accessMask,
                                     is_valid=True,
                                     is_character_key=True)

                        key.save()

                    else:
                        key = APIKey.objects.get(user=request.user, keyid=api_id, vcode=api_verification_code)

                    # If char already is assigned to another key, just move it
                    try:
                        char_to_move = Character.objects.get(id=char.characterID, user=request.user)
                        char_to_move.apikey_id = key.id
                        char_to_move.save()

                        # Update timers
                        manage_character_api_timers(char_to_move)

                        added_chars = True

                    except Character.DoesNotExist:
                        # Add character
                        me = auth.character(char.characterID)
                        sheet = me.CharacterSheet()
                        i_stats['name'] = ""
                        i_stats['value'] = 0
                        for attr in attributes:
                            implant[attr] = i_stats

                        # have to check because if you don't have an implant in you get nothing back
                        try:
                            implant['memory'] = {'name': sheet.attributeEnhancers.memoryBonus.augmentatorName,
                                                 'value': sheet.attributeEnhancers.memoryBonus.augmentatorValue}
                        except:
                            pass
                        try:
                            implant['perception'] = {'name': sheet.attributeEnhancers.perceptionBonus.augmentatorName,
                                                     'value': sheet.attributeEnhancers.perceptionBonus.augmentatorValue}
                        except:
                            pass
                        try:
                            implant['intelligence'] = {'name': sheet.attributeEnhancers.intelligenceBonus.augmentatorName,
                                                       'value': sheet.attributeEnhancers.intelligenceBonus.augmentatorValue}
                        except:
                            pass
                        try:
                            implant['willpower'] = {'name': sheet.attributeEnhancers.willpowerBonus.augmentatorName,
                                                    'value': sheet.attributeEnhancers.willpowerBonus.augmentatorValue}
                        except:
                            pass
                        try:
                            implant['charisma'] = {'name': sheet.attributeEnhancers.charismaBonus.augmentatorName,
                                                   'value': sheet.attributeEnhancers.charismaBonus.augmentatorValue}
                        except:
                            pass
                        try:
                            a_name = sheet.allianceName
                            a_id = sheet.allianceID

                        except:
                            a_name = ""
                            a_id = 0

                        new_char = Character(id=char.characterID,
                                            name=char.name,
                                            user=request.user,
                                            apikey=key,
                                            corp_name=sheet.corporationName,
                                            corp_id=sheet.corporationID,
                                            alliance_name=a_name,
                                            alliance_id=a_id,
                                            dob=pytz.utc.localize(datetime.datetime.utcfromtimestamp(sheet.DoB)),
                                            race=sheet.race,
                                            bloodline=sheet.bloodLine,
                                            ancestry=sheet.ancestry,
                                            gender=sheet.gender,
                                            clone_name=sheet.cloneName,
                                            clone_skill_points=sheet.cloneSkillPoints,
                                            balance=sheet.balance,
                                            implant_memory_name=implant['memory']['name'],
                                            implant_memory_bonus=implant['memory']['value'],
                                            implant_perception_name=implant['perception']['name'],
                                            implant_perception_bonus=implant['perception']['value'],
                                            implant_intelligence_name=implant['intelligence']['name'],
                                            implant_intelligence_bonus=implant['intelligence']['value'],
                                            implant_willpower_name=implant['willpower']['name'],
                                            implant_willpower_bonus=implant['willpower']['value'],
                                            implant_charisma_name=implant['charisma']['name'],
                                            implant_charisma_bonus=implant['charisma']['value'])
                        new_char.save()

                        new_apitimer = APITimer(character=new_char,
                                                corporation=None,
                                                apisheet="CharacterSheet",
                                                nextupdate=pytz.utc.localize(datetime.datetime.utcfromtimestamp(sheet._meta.cachedUntil)))
                        new_apitimer.save()

                        # Update other timers
                        manage_character_api_timers(new_char)

                        for skill in sheet.skills:
                            new_skill = CharSkill(character=new_char,
                                                  skill_id=skill.typeID,
                                                  skillpoints=skill.skillpoints,
                                                  level=skill.level)
                            new_skill.save()

                        added_chars = True

            # Change message depending on what we did
            if added_chars:
                messages.success(request, "Successfully added the selected character(s) to your account.")
            else:
                messages.info(request, "No characters were added.")
            return HttpResponseRedirect(reverse('manage_characters'))

    else:
        # This must be a corporation key then
        # Add key to DB if it does not exist
        if not APIKey.objects.filter(keyid=api_id, vcode=api_verification_code):

            # Handle keys which never expire
            try:
                key_expiration = datetime.datetime.fromtimestamp(key_info.key.expires)
            except:
                key_expiration = "9999-12-31 00:00:00"

            key = APIKey(user=request.user,
                         keyid=api_id,
                         vcode=api_verification_code,
                         expires=key_expiration,
                         accessmask=key_info.key.accessMask,
                         is_valid=True,
                         is_character_key=False)

            key.save()

            messages.success(request, "Successfully added your corporate key.")

        else:
            messages.info(request, "No keys were added.")

        return HttpResponseRedirect(reverse('manage_api_keys'))

    rcontext = RequestContext(request, {'chars': characters})
    return render_to_response('api_character.haml', rcontext)

Example 179

Project: oh-mainline
Source File: comments.py
View license
@csrf_protect
@require_POST
def post_comment(request, next=None, using=None):
    """
    Post a comment.

    HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
    errors a preview template, ``comments/preview.html``, will be rendered.
    """
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.get_username()
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest("Missing content_type or object_pk field.")
    try:
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.using(using).get(pk=object_pk)
    except TypeError:
        return CommentPostBadRequest(
            "Invalid content_type value: %r" % escape(ctype))
    except AttributeError:
        return CommentPostBadRequest(
            "The given content-type %r does not resolve to a valid model." % \
                escape(ctype))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type %r and object PK %r exists." % \
                (escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError) as e:
        return CommentPostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
                (escape(ctype), escape(object_pk), e.__class__.__name__))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Construct the comment form
    form = comments.get_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: %s" % \
                escape(str(form.security_errors())))

    # If there are errors or if we requested a preview show the comment
    if form.errors or preview:
        template_list = [
            # These first two exist for purely historical reasons.
            # Django v1.0 and v1.1 allowed the underscore format for
            # preview templates, so we have to preserve that format.
            "comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.module_name),
            "comments/%s_preview.html" % model._meta.app_label,
            # Now the usual directory based template hierarchy.
            "comments/%s/%s/preview.html" % (model._meta.app_label, model._meta.module_name),
            "comments/%s/preview.html" % model._meta.app_label,
            "comments/preview.html",
        ]
        return render_to_response(
            template_list, {
                "comment": form.data.get("comment", ""),
                "form": form,
                "next": data.get("next", next),
            },
            RequestContext(request, {})
        )

    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(
        sender=comment.__class__,
        comment=comment,
        request=request
    )

    for (receiver, response) in responses:
        if response == False:
            return CommentPostBadRequest(
                "comment_will_be_posted receiver %r killed the comment" % receiver.__name__)

    # Save the comment and signal that it was saved
    comment.save()
    signals.comment_was_posted.send(
        sender=comment.__class__,
        comment=comment,
        request=request
    )

    return next_redirect(request, fallback=next or 'comments-comment-done',
        c=comment._get_pk_val())

Example 180

Project: zorna
Source File: views.py
View license
@login_required()
def edit_story(request, story):
    allowed_objects = get_allowed_objects(
            request.user, ArticleCategory, 'manager')
    try:
        story = ArticleStory.objects.select_related().get(pk=story)
        categories = story.categories.all()
        intersect = set(allowed_objects).intersection( set([category.pk for category in categories]))
        if story.owner != request.user and not intersect:
            return HttpResponseRedirect('/')
    except Exception as e:
        print e
        return HttpResponseRedirect('/')

    attachments = story.articleattachments_set.all()
    if request.method == 'POST':
        if 'bdelstory' in request.POST:
            story.articleattachments_set.all().delete()
            pk = story.pk
            story.delete()
            try:
                shutil.rmtree(u"%s/%s" % (get_upload_articles_images(), pk))
            except:
                pass
            try:
                shutil.rmtree(u"%s/%s" % (get_upload_articles_files(), pk))
            except:
                pass
            return HttpResponseRedirect(reverse('writer_stories_list', args=[]))

        form_story = ArticleStoryForm(
            request.POST, request.FILES, instance=story, request=request)
        if form_story.is_valid():
            if 'selected_image' in request.POST:
                story.image.delete()
                try:
                    shutil.rmtree(u"%s/%s" % (get_upload_articles_images(), story.pk))
                except:
                    pass
            if 'image' in request.FILES:
                story.mimetype = request.FILES['image'].content_type
            else:
                image_file = None

            story.modifier = request.user
            story.save()

            story.categories.clear()
            selected_categories = request.POST.getlist('_selected_action')
            story.categories = selected_categories

        form_story = ArticleStoryForm(instance=story, request=request)

        if len(attachments) < 2:
            fa_set = formset_factory(
                ArticleAttachmentsForm, extra=2 - len(attachments))
            form_attachments_set = fa_set(request.POST, request.FILES)
            if form_attachments_set.is_valid():
                for i in range(0, form_attachments_set.total_form_count()):
                    form = form_attachments_set.forms[i]
                    try:
                        file = request.FILES['form-' + str(
                            i) + '-attached_file']
                        attachment = ArticleAttachments(description=form.cleaned_data[
                                                        'description'], mimetype=file.content_type)
                        attachment.article = story
                        attachment.save()
                        attachment.attached_file.save(file.name, file)
                    except:
                        pass

        if 'selected_attachments' in request.POST:
            att = request.POST.getlist('selected_attachments')
            ArticleAttachments.objects.filter(pk__in=att).delete()
        attachments = story.articleattachments_set.all()
        extra = len(attachments)
        if extra < 2:
            fa_set = formset_factory(ArticleAttachmentsForm, extra=2 - extra)
            form_attachments_set = fa_set()
        else:
            form_attachments_set = None

        tags = map(int, request.POST.getlist('article_tags[]'))
        story.tags.clear()
        tags = ArticleTags.objects.filter(pk__in=tags)
        story.tags.add(*tags)
        if story.categories:
            notify_users(request, story, story.categories.all(), False)

    else:
        form_story = ArticleStoryForm(instance=story, request=request)
        extra = len(attachments)
        if extra < 2:
            fa_set = formset_factory(ArticleAttachmentsForm, extra=2 - extra)
            form_attachments_set = fa_set()
        else:
            form_attachments_set = None

    tags = ArticleTags.objects.all()
    story_tags = story.tags.all()
    for tag in tags:
        if tag in story_tags:
            tag.checked = True
    context = RequestContext(request)
    extra_context = {'form_story': form_story,
                     'story': story,
                     'tags': tags,
                     'form_attachments': form_attachments_set,
                     'attachments': attachments,
                     'categories': [c.pk for c in categories],
                     }
    return render_to_response('articles/edit_article.html', extra_context, context_instance=context)

Example 181

Project: otm-legacy
Source File: views.py
View license
def create_profile(request, form_class=None, success_url=None,
                   template_name='profiles/create_profile.html',
                   extra_context=None):
    """
    Create a profile for the current user, if one doesn't already
    exist.
    
    If the user already has a profile, as determined by
    ``request.user.get_profile()``, a redirect will be issued to the
    :view:`profiles.views.edit_profile` view. If no profile model has
    been specified in the ``AUTH_PROFILE_MODULE`` setting,
    ``django.contrib.auth.models.SiteProfileNotAvailable`` will be
    raised.
    
    **Optional arguments:**
    
    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``form_class``
        The form class to use for validating and creating the user
        profile. This form class must define a method named
        ``save()``, implementing the same argument signature as the
        ``save()`` method of a standard Django ``ModelForm`` (this
        view will call ``save(commit=False)`` to obtain the profile
        object, and fill in the user before the final save). If the
        profile object includes many-to-many relations, the convention
        established by ``ModelForm`` of using a method named
        ``save_m2m()`` will be used, and so your form class should
        also define this method.
        
        If this argument is not supplied, this view will use a
        ``ModelForm`` automatically generated from the model specified
        by ``AUTH_PROFILE_MODULE``.
    
    ``success_url``
        The URL to redirect to after successful profile creation. If
        this argument is not supplied, this will default to the URL of
        :view:`profiles.views.profile_detail` for the newly-created
        profile object.
    
    ``template_name``
        The template to use when displaying the profile-creation
        form. If not supplied, this will default to
        :template:`profiles/create_profile.html`.
    
    **Context:**
    
    ``form``
        The profile-creation form.
    
    **Template:**
    
    ``template_name`` keyword argument, or
    :template:`profiles/create_profile.html`.
    
    """
    try:
        profile_obj = request.user.get_profile()
        return HttpResponseRedirect(reverse('profiles_edit_profile'))
    except ObjectDoesNotExist:
        pass
    
    #
    # We set up success_url here, rather than as the default value for
    # the argument. Trying to do it as the argument's default would
    # mean evaluating the call to reverse() at the time this module is
    # first imported, which introduces a circular dependency: to
    # perform the reverse lookup we need access to profiles/urls.py,
    # but profiles/urls.py in turn imports this module.
    #
    
    if success_url is None:
        success_url = reverse('profiles_profile_detail',
                              kwargs={ 'username': request.user.username })
    if form_class is None:
        form_class = utils.get_profile_form()
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            profile_obj = form.save(commit=False)
            profile_obj.user = request.user
            profile_obj.save()
            if hasattr(form, 'save_m2m'):
                form.save_m2m()
            return HttpResponseRedirect(success_url)
    else:
        form = form_class()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    
    return render_to_response(template_name,
                              { 'form': form },
                              context_instance=context)

Example 182

Project: Arkestra
Source File: clean_plugins.py
View license
@login_required
def clean(request, slug = "dryrun"):
    # this dictionary stores the information for the conversions
    if slug == "execute":
        execute = True
    else:
        execute = False
    trashed_styles=[]
    trashed_nbsps=[]
    trashed_paragraphs=[]
    trashed_style_attributes=[]
    double_spaces=[]
    click_heres=[]
    
    for plugin in Text.objects.all():
        modified = False
                
        if "&#160;" in plugin.body:
            plugin.body = plugin.body.replace("&#160;", " ")
            trashed_nbsps.append(plugin)
            print plugin, "    nbsp"
            modified = True
        
        if u"\xa0" in plugin.body:
            plugin.body = plugin.body.replace(u"\xa0", " ")
            trashed_nbsps.append(plugin)
            print plugin, "    encoded nbsp"
            modified = True
        
        if "  " in plugin.body:
            # plugin.body = plugin.body.replace("  ", " ")
            plugin.body = ' '.join(plugin.body.split())
            double_spaces.append(plugin)
            modified = True
            print plugin, "    doublespace"

        if "<p></p>" in plugin.body or "<p> </p>" in plugin.body:
            plugin.body = plugin.body.replace("<p></p>", "")
            plugin.body = plugin.body.replace("<p> </p>", "")
            trashed_paragraphs.append(plugin)
            modified = True
            print plugin, "    empty p"


        if "click here".lower() in plugin.body.lower():
            click_heres.append(plugin)
            print plugin, "    click here"

        # soup = plugin.body
        soup = BeautifulSoup(''.join(plugin.body)) # soup it up
        style_elements = soup.findAll("style")  # find the element with that id in the HTML
        modified_soup = False
    
        if style_elements:
            [style_element.extract() for style_element in style_elements]
            print plugin, "    style element"
            trashed_styles.append(plugin)
            modified_soup = True

        for attribute in ["style", "width", "height", "align"]:
            
            illegal_attributes = soup.findAll(attrs={attribute: True})
            if illegal_attributes:
                for illegal_attribute in illegal_attributes:
                    print "-------------- illegal attribute --------------"
                    print plugin
                    print "was:", illegal_attribute
                    print "will delete attribute:", attribute, " which is:", illegal_attribute[attribute]
                    del illegal_attribute[attribute]
                    print "now:", illegal_attribute
                modified_soup = True
        if modified_soup:
            modified= True
            plugin.body = unicode(soup)                    

        
        if execute and modified:
            # print "Saving", plugin.cmsplugin_ptr_id, plugin
            plugin.save()
            
    return shortcuts.render_to_response(
        "housekeeping/statistics.html", {
            "execute": execute,
            "trashed_styles": trashed_styles,
            "trashed_nbsps": trashed_nbsps,
            "trashed_paragraphs": trashed_paragraphs,
            "double_spaces": double_spaces,
            "click_heres": click_heres,
            },
        RequestContext(request),
        )

Example 183

Project: tlsprober
Source File: views.py
View license
def SearchResults_doSearch(request):
	"""
	Search for number of results from a given run, matching given parameters
	Return the total, and optionally more detailed counts for specific
	elements (such as hostnames, IP domains, cipher suites, etc.)
	
	The actual search is done in summary_models
	""" 
	if request.method == 'POST': # If the form has been submitted...
		form = ResultForm(request.POST) # A form bound to the POST data
	elif request.method == 'GET': # If the form has been submitted...
		form = ResultForm(request.GET) # A form bound to the GET data
	if form.is_valid(): # All validation rules pass
		filter = {}
		summaries = {}
		
		summary = form.cleaned_data["run_to_use"]
		
		filters =  form.cleaned_data["conditions"]
		summary_entry = form.cleaned_data["summary"]
		protocol=  form.cleaned_data["protocol"]
		if "All" in protocol or not protocol:
			protocol = None

		ciphers = []		
		ciph =  form.cleaned_data["ciphers_include"]
		if ciph:
			for x in ciph:
				if x in ["AES", "RC4", "3DES"]:
					ciphers += ProbeData.CipherName.objects.filter(ciphername__startswith="TLS", ciphername__contains = "_"+x+"_").values_list("id",flat=True)
				else:
					ciphers += ProbeData.CipherName.objects.filter(ciphervalue = int(x)).values_list("id",flat=True)
			ciphers = ProbeData.CipherName.objects.filter(id__in = ciphers)

		ciphers_ex = []		
		ciph =  form.cleaned_data["ciphers_exclude"]
		if ciph:
			for x in ciph:
				if x in ["AES", "RC4", "3DES"]:
					ciphers_ex += ProbeData.CipherName.objects.filter(ciphername__startswith="TLS", ciphername__contains = "_"+x+"_").values_list("id",flat=True)
				else:
					ciphers_ex += ProbeData.CipherName.objects.filter(ciphervalue = int(x)).values_list("id",flat=True)
			ciphers_ex = ProbeData.CipherName.objects.filter(id__in = ciphers_ex)
		
		alexagroup = form.cleaned_data["alexagroup"]
		if not alexagroup:
			alexagroup = -1
		
		profile_q = None
		profile = int(request.GET.get("profile",0))
		if profile:
			profile_q = Q(result_entry__common_result=profile)
		else:
			profile = int(request.GET.get("bprofile",0)	)
			if profile:
				profile_q = Q(result_entry__common_result__basic_result=profile)
			else:
				profile = int(request.GET.get("fprofile",0))
				if profile:
					profile_q = Q(result_entry__common_result__fundamental_result=profile)
					
		extraparam = {}
		if profile_q:
			extraparam["limitresult"] = profile_q
			
		result = summary.GetAnalyze(filter=dict([(Results.ResultSummaryList.QUERY_CONDITION, form.cleaned_data["conditions"]),
										(Results.ResultSummaryList.QUERY_ALEXA_RESTRICT,alexagroup),
										] +
										 ([(Results.ResultSummaryList.QUERY_PROTOCOL_RESTRICT, protocol)] if protocol else [])+ 
										 ([(Results.ResultSummaryList.QUERY_RESTRICT_RUN,[x.part_of_run_id for x in form.cleaned_data["run_to_limit"]])] if form.cleaned_data["run_to_limit"] else [])+
										 ([(Results.ResultSummaryList.QUERY_CIPHER, ciphers)]  if ciphers else [])+
										 ([(Results.ResultSummaryList.QUERY_CIPHER_EXCLUDE, ciphers_ex)]  if ciphers_ex else [])
										), 
					summaries={
							"data":([summary_entry] if summary_entry != "Total" else []),
							 },
					**extraparam
					)
		
		value_fun = {
					Results.ResultSummaryList.RESULT_HOSTS:lambda x: x.servername.full_servername,
					Results.ResultSummaryList.RESULT_HOSTS_ALEXA:lambda x: x.servername.full_servername,
					Results.ResultSummaryList.RESULT_URLS_TEXT:lambda x: x.servername.full_servername,
					Results.ResultSummaryList.RESULT_HOST_RUNLIST:lambda x: (x.servername.servername, x.servername.port),
					Results.ResultSummaryList.RESULT_CONDITION:lambda x:dict(Results.ResultCondition.RESULTC_VALUES)[x.condition],
					Results.ResultSummaryList.RESULT_DOMAIN:lambda x: x.full_domain_name,
					Results.ResultSummaryList.RESULT_IP:lambda x: x.full_ip_mask,
					Results.ResultSummaryList.RESULT_PRIMARYAGENT:lambda x: x.agent_name,
					Results.ResultSummaryList.RESULT_SHORTPRIMARYAGENT:lambda x: x.agent_name,
					Results.ResultSummaryList.RESULT_SECONDARYAGENT:lambda x: x.agent_name,
					Results.ResultSummaryList.RESULT_SHORTSECONDARYAGENT:lambda x: x.agent_name,
					Results.ResultSummaryList.RESULT_CIPHER:lambda x: x.ciphername,
					Results.ResultSummaryList.RESULT_CIPHERGROUP:lambda x:  " ".join(sorted([y.ciphername for y in x.cipher_suites.cipher_suites.all()])),
					Results.ResultSummaryList.RESULT_PROTOCOLS:lambda x: dict(Results.ResultCondition.RESULTC_VALUES)[x.condition],
					Results.ResultSummaryList.RESULT_HOST_PROFILES:lambda x:x.key,
					Results.ResultSummaryList.RESULT_HOST_BASEPROFILES:lambda x:x.key,
					Results.ResultSummaryList.RESULT_HOST_FUNDPROFILES:lambda x:x.key,
					}[summary_entry] if summary_entry != "Total" else None
		data = result.get("data",[]) if summary_entry != "Total" else []
		if not data:
			data = []

						
		entries = [ (
						value_fun(x),
						x.filtered_count, 
						x.total_count, 
						(float(x.filtered_count)/float(x.total_count) if x.total_count else 0 )*100, 
						x,
						)						
						for x in data
					]
		if summary_entry in [Results.ResultSummaryList.RESULT_HOSTS_ALEXA, Results.ResultSummaryList.RESULT_URLS_TEXT, Results.ResultSummaryList.RESULT_HOST_RUNLIST]:
			entries.sort(key = lambda x:(x[-1].servername.alexa_rating if x[-1].servername.alexa_rating >0 else 100000000,x[-1].servername.full_servername))
		else:
			entries.sort(key = lambda x:(-x[1], x[0]))

		if summary_entry ==Results.ResultSummaryList.RESULT_URLS_TEXT:
			response = HttpResponse(mimetype="text/plain")
			response["Content-Disposition"] = "attachment; filename=urls.txt"
			
			for x in entries:
				response.write('https://'+x[-1].servername.servername+":"+str(x[-1].servername.port)+'/\n')
					
			return response  
		elif summary_entry ==Results.ResultSummaryList.RESULT_HOST_RUNLIST:
			response = HttpResponse(mimetype="text/csv")
			response["Content-Disposition"] = "attachment; filename=runlist.csv"
			
			import csv
			
			writer = csv.writer(response)
			i = 0
			for x in entries:
				i+=1
				writer.writerow([i] + list(x[0]))
					
			return response  
		elif summary_entry in [Results.ResultSummaryList.RESULT_HOST_PROFILES, Results.ResultSummaryList.RESULT_HOST_BASEPROFILES, Results.ResultSummaryList.RESULT_HOST_FUNDPROFILES]:
			return render_to_response('searchprofileresults.html', {
				"run":summary.part_of_run_id,
				"matching":result["_matching"],
				"total":result["_total"],
				"match_percentage":(float(result["_matching"])/float(result["_total"]) if result["_total"] else 0 )*100,
				"entries":entries,
				"debug_output":[x for x in connection.queries],
			
			})
				

		return render_to_response('searchresults.html', {
			"matching":result["_matching"],
			"total":result["_total"],
			"show_alexa":summary_entry == Results.ResultSummaryList.RESULT_HOSTS_ALEXA,
			"match_percentage":(float(result["_matching"])/float(result["_total"]) if result["_total"] else 0 )*100,
			"entries":entries,
			"debug_output":[x for x in connection.queries],
			
		})
	else:
		return 	SearchResults(request, method = request.method)

Example 184

Project: PyClassLessons
Source File: comments.py
View license
@csrf_protect
@require_POST
def post_comment(request, next=None, using=None):
    """
    Post a comment.

    HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
    errors a preview template, ``comments/preview.html``, will be rendered.
    """
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.get_username()
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest("Missing content_type or object_pk field.")
    try:
        model = apps.get_model(ctype)
        target = model._default_manager.using(using).get(pk=object_pk)
    except TypeError:
        return CommentPostBadRequest(
            "Invalid content_type value: %r" % escape(ctype))
    except LookupError:
        return CommentPostBadRequest(
            "The given content-type %r does not resolve to a valid model." % \
                escape(ctype))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type %r and object PK %r exists." % \
                (escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError) as e:
        return CommentPostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
                (escape(ctype), escape(object_pk), e.__class__.__name__))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Construct the comment form
    form = comments.get_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: %s" % \
                escape(str(form.security_errors())))

    # If there are errors or if we requested a preview show the comment
    if form.errors or preview:
        template_list = [
            # These first two exist for purely historical reasons.
            # Django v1.0 and v1.1 allowed the underscore format for
            # preview templates, so we have to preserve that format.
            "comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.model_name),
            "comments/%s_preview.html" % model._meta.app_label,
            # Now the usual directory based template hierarchy.
            "comments/%s/%s/preview.html" % (model._meta.app_label, model._meta.model_name),
            "comments/%s/preview.html" % model._meta.app_label,
            "comments/preview.html",
        ]
        return render_to_response(
            template_list, {
                "comment": form.data.get("comment", ""),
                "form": form,
                "next": data.get("next", next),
            },
            RequestContext(request, {})
        )

    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(
        sender=comment.__class__,
        comment=comment,
        request=request
    )

    for (receiver, response) in responses:
        if response == False:
            return CommentPostBadRequest(
                "comment_will_be_posted receiver %r killed the comment" % receiver.__name__)

    # Save the comment and signal that it was saved
    comment.save()
    signals.comment_was_posted.send(
        sender=comment.__class__,
        comment=comment,
        request=request
    )

    return next_redirect(request, fallback=next or 'comments-comment-done',
        c=comment._get_pk_val())

Example 185

Project: repowatcher
Source File: authed.py
View license
@login_required
def authed_category_watched(request,category):
    """has all github repos and the latest 30 events for a username with a specific category"""
    repo_link_type, _ = LinkType.objects.get_or_create(name = "starred")
    owned = False
    category = urllib.unquote(category).lower()
    github_watched_filtered = []
    bitbucket_watched_filtered = []
    github_repo_events = []
    bitbucket_repo_events = []
    user = request.user
    repository_user = None
    github_username = None
    bitbucket_username = None
    bitbucket_authed = True
    github_authed = True
    watched_filtered = []
    try:
        github_username = user.social_auth.get(provider='github').extra_data['username']
        github_provider = GithubProvider(user)
        github_watched_filtered, github_repository_user = github_provider.retrieve_category_repositories(github_username, category, "starred")
        watched_filtered.extend(github_watched_filtered)
        github_repository_user.save()
        if len(github_watched_filtered) == 0:
            watched = github_provider.get_repositories(github_username, "starred")

            count = 0
            for repo in watched:
                update = False
                try:
                    repository = Repository.objects.get(host_slug= 'github/'+repo['owner'].lower() + '/' + repo['name'].lower())
                except ObjectDoesNotExist:
                    update = True
                    repository = Repository()
                if update or (datetime.now() - repository.last_modified) > timedelta(days = 1):
                    repository = github_provider.create_or_update_repository_details(repo, repository)
                    if not repository.private:
                        repository.save()
                if repository.language == category:
                    github_watched_filtered.append(repository)
                    if not repository.private:
                        count += 1
                if not repository.private:
                    RepositoryUserRepositoryLink.objects.get_or_create(user = repository_user, repository = repository, link_type = repo_link_type)
            watched_filtered.extend(github_watched_filtered)
            watched_filtered.sort(key=lambda x: x.watchers, reverse = True)
            RepositoryCategory.objects.get_or_create(name = category.lower())
            github_repository_user.starred = count
            github_repository_user.save()


        # Get repository events
        github_repo_events = github_provider.get_repositories_events(github_watched_filtered)
        for github_repo_event in github_repo_events:
            github_repo_event['host'] = 'github'
            github_repo_event['created_on'] = dateutil.parser.parse(github_repo_event['created_at'])
    except ObjectDoesNotExist:
        github_authed = False

    user = request.user
    try:
        bitbucket_username = user.social_auth.get(provider='bitbucket').extra_data['username']
        bitbucket_provider = BitbucketProvider(user)
        bitbucket_watched_filtered, bitbucket_repository_user = bitbucket_provider.retrieve_watched_category_repositories(bitbucket_username, category)
        watched_filtered.extend(bitbucket_watched_filtered)
        bitbucket_repository_user.save()
        if len(bitbucket_watched_filtered) == 0:
            watched = bitbucket_provider.get_watched_repositories(bitbucket_username)
            for repo in watched:
                update = False
                try:
                    repository = Repository.objects.get(host_slug= 'bitbucket/'+repo['owner'].lower() + '/' + repo['name'].lower())
                except ObjectDoesNotExist:
                    update = True
                    repository = Repository()
                if update or (datetime.now() - repository.last_modified) > timedelta(days = 1):
                    bitbucket_provider.create_or_update_repository_details(repo, repository)
                    if not repository.private:
                        repository.save()
                if repository.language == category:
                    bitbucket_watched_filtered.append(repository)
            RepositoryCategory.objects.get_or_create(name = category)
            watched_filtered.extend(bitbucket_watched_filtered)
            watched_filtered.sort(key=lambda x: x.watchers, reverse = True)
        bitbucket_repo_events = bitbucket_provider.get_repositories_events(bitbucket_watched_filtered)
        for bitbucket_repo_event in bitbucket_repo_events:
            bitbucket_repo_event['host'] = 'bitbucket'
            bitbucket_repo_event['created_on'] = dateutil.parser.parse(bitbucket_repo_event['utc_created_on'])
    except ObjectDoesNotExist:
        bitbucket_authed = False
    repo_events = sorted(github_repo_events + bitbucket_repo_events,key=itemgetter('created_on'), reverse = True)[:30]
    if bitbucket_authed or github_authed:
        return render_to_response('username_category_watched.html', {'github_username': github_username,'github_authed': github_authed,'bitbucket_username':bitbucket_username, 'bitbucket_authed':bitbucket_authed, 'watched':watched_filtered, 'category':category, 'repo_events':repo_events,'owned':owned},context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect(reverse('repowatcher.main.views.authed'))

Example 186

Project: aemanager
Source File: views.py
View license
@settings_required
@subscription_required
@commit_on_success
def invoice_create_or_edit(request, id=None, customer_id=None, proposal_id=None):
    if id:
        title = _('Edit an invoice')
        invoice = get_object_or_404(Invoice, pk=id, owner=request.user)
        customer = invoice.customer
    else:
        title = _('Draw up an invoice')
        invoice = None
        """
        in case of invoice creation, if a customer_id is not provided by url
        we look for it in the autocomplete field (case of direct invoice draw up
        without proposal)
        """
        if request.method == 'POST':
            autocompleted_customer_id = request.POST.get('contact-customer_id')
            if not customer_id:
                customer_id = autocompleted_customer_id
        if customer_id:
            customer = get_object_or_404(Contact, pk=customer_id, owner=request.user)
        else:
            customer = None

    address = None
    original_customer_name = None
    if customer:
        address = customer.address
        original_customer_name = customer.name

    proposal = None
    if proposal_id:
        proposal = get_object_or_404(Proposal,
                                     pk=proposal_id,
                                     project__customer=customer,
                                     owner=request.user,
                                     state__in=[PROPOSAL_STATE_ACCEPTED])

    InvoiceRowFormSet = inlineformset_factory(Invoice,
                                              InvoiceRow,
                                              form=InvoiceRowForm,
                                              fk_name="invoice",
                                              extra=1)

    proposals = Proposal.objects.get_proposals_for_invoice(customer, request.user, invoice)

    if request.method == 'POST':
        contactForm = ContactQuickCreateForm(request.POST,
                                             instance=customer,
                                             prefix="contact")
        if customer:
            contactForm.setToEditMode()

        addressForm = AddressForm(request.POST,
                                  instance=address,
                                  prefix="address")
        invoiceForm = InvoiceForm(request.POST,
                                  instance=invoice,
                                  prefix="invoice")
        invoicerowformset = InvoiceRowFormSet(request.POST,
                                              instance=invoice)
        for invoicerowform in invoicerowformset.forms:
            invoicerowform.fields['proposal'].queryset = proposals

        if contactForm.is_valid() and addressForm.is_valid() and \
           invoiceForm.is_valid() and invoicerowformset.is_valid():
            try:
                user = request.user

                address = addressForm.save(commit=False)
                address.save(user=user)

                customer = contactForm.save(commit=False)
                if not customer.contact_type:
                    customer.contact_type = CONTACT_TYPE_COMPANY
                # restore original name since it shouldn't be changed in invoice
                if original_customer_name:
                    customer.name = original_customer_name
                customer.address_id = address.id
                customer.save(user=user)

                invoice = invoiceForm.save(commit=False)
                invoice.customer = customer
                if invoice.paid_date:
                    invoice.state = INVOICE_STATE_PAID
                invoice.save(user=user)
                invoiceForm.save_m2m()
                for invoicerowform in invoicerowformset.forms:
                    if invoicerowform not in invoicerowformset.deleted_forms and invoicerowform.cleaned_data:
                        invoicerow = invoicerowform.save(commit=False)
                        invoicerow.invoice = invoice
                        invoicerow.save(user=user)

                        if invoicerow.proposal and invoicerow.balance_payments and invoice.paid_date:
                            invoicerow.proposal.state = PROPOSAL_STATE_BALANCED
                            invoicerow.proposal.save()

                for deleted_invoicerowform in invoicerowformset.deleted_forms:
                    deleted_invoicerowform.instance.delete()

                invoice.check_amounts()

                messages.success(request, _('The invoice has been saved successfully'))
                if invoice.paid_date and invoice.paid_date > datetime.date.today():
                    messages.warning(request, _("Paid date is in the future, is this normal ?"))
                if invoice.execution_begin_date and invoice.execution_end_date and invoice.execution_begin_date > invoice.execution_end_date:
                    messages.warning(request, _("Execution begin date is greater than execution end date, is this normal ?"))
                if invoice.penalty_date and invoice.penalty_date < invoice.payment_date:
                    messages.warning(request, _("Payment date is greater than penalty date, is this normal ?"))
                return redirect(reverse('invoice_detail', kwargs={'id': invoice.id}))
            except InvoiceRowAmountError:
                transaction.rollback()
                messages.error(request, _("Amounts invoiced can't be greater than proposals remaining amounts"))
            except InvoiceIdNotUniqueError:
                transaction.rollback()
                invoiceForm._errors["invoice_id"] = invoiceForm.error_class([_("Invoice id must be unique")])
        else:
            messages.error(request, _('Data provided are invalid'))
    else:
        next_invoice_id = Invoice.objects.get_next_invoice_id(request.user)
        initial_data = None
        if not invoice:
            initial_data = {'invoice_id': next_invoice_id,
                            'edition_date': datetime.datetime.now()}
            if proposal:
                initial_data['execution_begin_date'] = proposal.begin_date
                initial_data['execution_end_date'] = proposal.end_date

        contactForm = ContactQuickCreateForm(instance=customer,
                                             prefix="contact")
        if customer:
            contactForm.setToEditMode()
        addressForm = AddressForm(instance=address,
                                  prefix="address")

        invoiceForm = InvoiceForm(instance=invoice,
                                  prefix="invoice",
                                  initial=initial_data)

        initial_row_data = None
        if proposal:
            initial_row_data = []
            for proposal_row in proposal.proposal_rows.all():
                initial_row_data.append({'label': proposal_row.label,
                                         'proposal': proposal,
                                         'balance_payments': True,
                                         'category': proposal_row.category,
                                         'quantity': proposal_row.quantity,
                                         'detail': proposal_row.detail,
                                         'unit_price': proposal_row.unit_price})
            InvoiceRowFormSet.extra = len(initial_row_data) + 1

        invoicerowformset = InvoiceRowFormSet(instance=invoice)
        i = 0
        for invoicerowform in invoicerowformset.forms:
            invoicerowform.fields['proposal'].queryset = proposals
            # for all rows except last
            if i < InvoiceRowFormSet.extra - 1:
                invoicerowform.initial = initial_row_data[i]
                i = i + 1


    return render_to_response('invoice/edit.html',
                              {'active': 'accounts',
                               'title': title,
                               'from_proposal': proposal,
                               'contactForm': contactForm,
                               'addressForm': addressForm,
                               'invoiceForm': invoiceForm,
                               'invoicerowformset': invoicerowformset},
                               context_instance=RequestContext(request))

Example 187

Project: tradeschool
Source File: views.py
View license
def course_add(request, branch_slug=None):
    """
    """
    branch = get_object_or_404(Branch, slug=branch_slug)

    if request.method == 'POST':
        BarterItemFormSet = formset_factory(
            BarterItemForm, extra=5, formset=BaseBarterItemFormSet)
        barter_item_formset = BarterItemFormSet(data=request.POST, prefix="item", branch=branch)
        course_form = CourseForm(request.POST, prefix="course")
        teacher_form = TeacherForm(request.POST, prefix="teacher")
        time_form = TimeSelectionForm(
            data=request.POST,
            prefix="time",
        )
        time_form.fields['time'].queryset = Time.objects.filter(branch=branch)

        if barter_item_formset.is_valid() \
                and course_form.is_valid() \
                and teacher_form.is_valid() \
                and time_form.is_valid():
            # process teacher
            teacher = teacher_form.save(commit=False)
            teacher_data = teacher_form.cleaned_data

            # create a slug for the teacher object
            teacher_data['slug'] = unique_slugify(Teacher, teacher.fullname)

            # check if the submitting teacher already exists in the system
            # we determine an existing teacher by their email
            teacher = Teacher.objects.filter(email=teacher.email)

            # if this is an existing teacher,
            # update the field with the data from the form
            if teacher.exists():
                teacher = teacher[0]
                teacher.fullname = teacher_form.cleaned_data['fullname']
                teacher.bio = teacher_form.cleaned_data['bio']
                teacher.website = teacher_form.cleaned_data['website']
                teacher.phone = teacher_form.cleaned_data['phone']
            else:
                teacher = Person.objects.create_user(**teacher_data)

            teacher.is_teacher = True

            # save teacher
            teacher.save()

            # add a teacher-branch relationship to the current branch
            teacher.branches.add(branch)

            # process course
            course = course_form.save(commit=False)
            course_data = course_form.cleaned_data

            # create a slug for the course object
            course_data['slug'] = unique_slugify(Course, course.title)

            # add the teacher as a foreign key
            course_data['teacher'] = teacher

            # course branch
            course_data['branch'] = branch

            # course status
            course_data['status'] = 'pending'

            # save time
            selected_time = time_form.cleaned_data['time']
            course_data['start_time'] = selected_time.start_time
            course_data['end_time'] = selected_time.end_time

            if selected_time.venue is not None:
                course_data['venue'] = selected_time.venue
            else:
                try:
                    course_data['venue'] = branch.venue_set.all()[0]
                except IndexError:
                    pass

            # save course
            course = Course(**course_data)
            course.save()

            # save barter items
            for barter_item_form in barter_item_formset:
                barter_item_form_data = barter_item_form.cleaned_data

                # check if the submitted barter item
                # already exists in the system.
                # we determine an existing barter item by its title
                barter_item, barter_item_created = BarterItem.objects.get_or_create(
                    title=barter_item_form_data['title'],
                    course=course,
                    defaults=barter_item_form_data
                )
                barter_item.save()

            # send confirmation email to teacher
            course.email_teacher(course.teacherconfirmation)

            # delete the selected time slot
            Time.objects.get(pk=selected_time.pk).delete()

            # redirect to thank you page
            return HttpResponseRedirect(reverse_lazy(
                course_submitted,
                kwargs={
                    'course_slug': course.slug,
                    'branch_slug': branch.slug
                })
            )

    else:
        BarterItemFormSet = formset_factory(
            BarterItemForm, extra=5, formset=BaseBarterItemFormSet)
        barter_item_formset = BarterItemFormSet(prefix="item", branch=branch)
        course_form = CourseForm(prefix="course")
        teacher_form = TeacherForm(prefix="teacher")
        time_form = TimeSelectionForm(prefix="time")
        time_form.fields['time'].queryset = Time.objects.filter(branch=branch)

    view_templates = branch_templates(
        branch, 'course_submit.html', 'subpage.html')

    return render_to_response(view_templates.template.name, {
        'branch': branch,
        'barter_item_formset': barter_item_formset,
        'course_form': course_form,
        'teacher_form': teacher_form,
        'time_form': time_form,
        'templates': view_templates
    }, context_instance=RequestContext(request))

Example 188

Project: zorna
Source File: views.py
View license
def edit_page(request):
    b_pages_manager, b_templates_manager = get_pages_access(request.user)
    if b_pages_manager:
        from zorna.utils import get_context_text
        page = request.REQUEST.get('file', '')
        path_tf = os.path.join(
            settings.PROJECT_PATH, settings.ZORNA_CONTENT, page)
        header, text = get_context_text(path_tf)
        blocks = get_blocks(request, text)
        import yaml
        context_yaml = yaml.load(header)
        if request.method == 'POST':
            document = ''
            try:
                import codecs
                lflr = '\r\n'
                fd = codecs.open(path_tf, "r+", "utf-8")
                text = fd.read()
                to_add = []
                for key, value in request.POST.iteritems():
                    if key[0:2] == '__':
                        document = document + ' ' + value
                        repl = "%s block %s %s\n%s\n%s endblock %s" % (
                            '{%', key, '%}', value, '{%', '%}')
                        pre = re.compile(r'(%s\s*block\s*%s\s*%s)(.*?)(%s\s*endblock.*?\s*%s)' % (re.escape(
                            '{%'), key, re.escape('%}'), re.escape('{%'), re.escape('%}')), re.M | re.DOTALL)
                        if pre.search(text):
                            text = pre.sub(repl, text)
                        else:
                            to_add.append(repl + lflr)

                description = request.POST.get(
                    "description", '').replace('\n', '')
                tab_ctx = {'title': request.POST.get("title", ''), 'description': description, 'keywords': request.POST.get(
                    "keywords", ''), 'created': str(datetime.datetime.now()), 'author': str(request.user.pk)}
                if not header:
                    context_yaml = tab_ctx
                else:
                    context_yaml.update(tab_ctx)
                result = ''
                for k, v in context_yaml.iteritems():
                    if k in request.POST:
                        v = request.POST.get(k, '').replace('\n', '')
                    result = result + k + ": '%s'%s" % (
                        v.replace("'", "''"), lflr)
                ctx = "%s zorna %s%s%s%s" % ('{%', lflr, result, lflr, '%}')
                pre = re.compile(r'(%s\s*zorna)(.*?)(\s*%s)' % (
                    re.escape('{%'), re.escape('%}')), re.M | re.DOTALL)
                if pre.search(text):
                    text = pre.sub(ctx, text)
                else:
                    text = text + lflr + ctx

                what = request.REQUEST.get('what', 'save')
                if what == 'save':
                    fd.seek(0)
                    fd.truncate()
                    fd.write(text)
                    fd.close()
                    zorna_page_save.send(
                        None, created=False, content=document, title=request.POST.get("title", page), url=page)
                else:
                    # create temporary file
                    head, tail = os.path.split(page)
                    if head:
                        head = head + '/'
                    temp_page = head + 'temp-%s' % tail
                    path_tempf = os.path.join(
                        settings.PROJECT_PATH, settings.ZORNA_CONTENT, temp_page)
                    fd = open(path_tempf, 'w+')
                    fd.write(text.encode('UTF-8'))
                    fd.close()
                    return HttpResponseRedirect(reverse('preview_page', args=[os.path.splitext(temp_page)[0]]))
            except Exception as e:
                ret = {'status': 'error', 'message': 'Error: %s' % str(e)}
                return HttpResponse(simplejson.dumps(ret))

            ret = {'status': 'success', 'message':
                   'Your changes have been saved successfully.'}
            return HttpResponse(simplejson.dumps(ret))

        form = PageEditFileForm(extra=blocks, request=request)
        if header:
            initial_data = {}
            initial_data['title'] = context_yaml[
                'title'] if 'title' in context_yaml else ''
            initial_data['description'] = context_yaml[
                'description'] if 'description' in context_yaml else ''
            initial_data['keywords'] = context_yaml[
                'keywords'] if 'keywords' in context_yaml else ''
            for e in ['author', 'created', 'title', 'keywords', 'description']:
                if e in context_yaml:
                    del context_yaml[e]
            form_context = PageEditFileContextForm(
                initial=initial_data, extra=context_yaml)
        else:
            form_context = None
        extra_context = {'form_context': form_context, 'form':
                         form, 'cdir_components': format_components(page), 'template_file': page}
        context = RequestContext(request)
        return render_to_response('pages/fm_edit_file.html', extra_context, context_instance=context)
    else:
        return HttpResponse('')

Example 189

Project: ganeti_webmgr
Source File: views.py
View license
@login_required
def modify_confirm(request, cluster_slug, instance):
    vm, cluster = get_vm_and_cluster_or_404(cluster_slug, instance)

    hv = get_hypervisor(vm)
    if hv == 'kvm':
        hv_form = KvmModifyVirtualMachineForm
    elif hv == 'xen-pvm':
        hv_form = PvmModifyVirtualMachineForm
    elif hv == 'xen-hvm':
        hv_form = HvmModifyVirtualMachineForm
    else:
        hv_form = None
        # XXX no matter what, we're gonna call hv_form() and die. Let's do it
        # louder than usual. >:3
        msg = "Hey, guys, implementation error in views/vm.py:modify_confirm"
        raise RuntimeError(msg)

    user = request.user
    power = user.is_superuser or user.has_any_perms(vm, ['admin', 'power'])
    if not (user.is_superuser or user.has_any_perms(vm, ['admin', 'modify'])
            or user.has_perm('admin', cluster)):
        raise PermissionDenied(
            _('You do not have permissions to edit this virtual machine'))

    if request.method == "POST":
        if 'edit' in request.POST:
            return HttpResponseRedirect(
                reverse("instance-modify",
                        args=[cluster.slug, vm.hostname]))
        elif 'reboot' in request.POST or 'save' in request.POST:
            form = ModifyConfirmForm(request.POST)
            form.session = request.session
            form.owner = vm.owner
            form.vm = vm
            form.cluster = cluster

            if form.is_valid():
                beparams = {}
                data = form.cleaned_data
                rapi_dict = data['rapi_dict']
                nics = rapi_dict.pop('nics')
                beparams['vcpus'] = rapi_dict.pop('vcpus')
                if has_balloonmem(cluster):
                    beparams['maxmem'] = rapi_dict.pop('maxmem')
                    beparams['minmem'] = rapi_dict.pop('minmem')
                else:
                    beparams['memory'] = rapi_dict.pop('memory')
                os_name = rapi_dict.pop('os')
                notes = rapi_dict.pop('notes')
                job_id = cluster.rapi.ModifyInstance(
                    instance,
                    nics=nics,
                    os_name=os_name,
                    hvparams=rapi_dict,
                    beparams=beparams)
                # Create job and update message on virtual machine detail page
                job = Job.objects.create(job_id=job_id,
                                         obj=vm,
                                         cluster=cluster)
                VirtualMachine.objects \
                    .filter(id=vm.id).update(last_job=job, ignore_cache=True,
                                             note_text=notes)
                # log information about modifying this instance
                log_action('EDIT', user, vm)
                if 'reboot' in request.POST and vm.info['status'] == 'running':
                    if power:
                        # Reboot the vm
                        job = vm.reboot()
                        log_action('VM_REBOOT', user, vm, job)
                    else:
                        raise PermissionDenied(
                            _("Sorry, but you do not have permission "
                              "to reboot this machine."))

                # Redirect to instance-detail
                return HttpResponseRedirect(
                    reverse("instance-detail",
                            args=[cluster.slug, vm.hostname]))

        elif 'cancel' in request.POST:
            # Remove session variables.
            if 'edit_form' in request.session:
                del request.session['edit_form']
            # Redirect to instance-detail
            return HttpResponseRedirect(
                reverse("instance-detail", args=[cluster.slug, vm.hostname]))

    elif request.method == "GET":
        form = ModifyConfirmForm()

    session = request.session

    if 'edit_form' not in request.session:
        return HttpResponseBadRequest('Incorrect Session Data')

    data = session['edit_form']
    info = vm.info
    hvparams = info['hvparams']

    old_set = dict(
        vcpus=info['beparams']['vcpus'],
        os=info['os'],
        notes=vm.note_text
    )
    if has_balloonmem(cluster):
        old_set['maxmem'] = info['beparams']['maxmem']
        old_set['minmem'] = info['beparams']['minmem']
    else:
        old_set['memory'] = info['beparams']['memory']
    nic_count = len(info['nic.links'])
    for i in xrange(nic_count):
        old_set['nic_link_%s' % i] = info['nic.links'][i]
        old_set['nic_mac_%s' % i] = info['nic.macs'][i]

    # Add hvparams to the old_set
    old_set.update(hvparams)

    instance_diff = {}
    fields = hv_form(vm, data).fields
    for key in data.keys():
        if key in ['memory', 'maxmem', 'minmem']:
            diff = compare(render_storage(old_set[key]),
                           render_storage(data[key]))
        elif key == 'os':
            oses = os_prettify([old_set[key], data[key]])
            if len(oses) > 1:
                """
                XXX - Special case for a cluster with two different types of
                  optgroups (i.e. Image, Debootstrap).
                  The elements at 00 and 10:
                    The optgroups
                  The elements at 010 and 110:
                    Tuple containing the OS Name and OS value.
                  The elements at 0101 and 1101:
                    String containing the OS Name
                """
                oses[0][1][0] = list(oses[0][1][0])
                oses[1][1][0] = list(oses[1][1][0])
                oses[0][1][0][1] = '%s (%s)' % (oses[0][1][0][1], oses[0][0])
                oses[1][1][0][1] = '%s (%s)' % (oses[1][1][0][1], oses[1][0])
                oses = oses[0][1] + oses[1][1]
                diff = compare(oses[0][1], oses[1][1])
            else:
                oses = oses[0][1]
                diff = compare(oses[0][1], oses[1][1])
            # diff = compare(oses[0][1], oses[1][1])
        if key in ['nic_count', 'nic_count_original']:
            continue
        elif key not in old_set.keys():
            diff = ""
            instance_diff[fields[key].label] = _('Added')
        else:
            diff = compare(old_set[key], data[key])

        if diff != "":
            label = fields[key].label
            instance_diff[label] = diff

    # remove mac if it has not changed
    for i in xrange(nic_count):
        if fields['nic_mac_%s' % i].label not in instance_diff:
            del data['nic_mac_%s' % i]

    # Repopulate form with changed values
    form.fields['rapi_dict'] = CharField(widget=HiddenInput,
                                         initial=json.dumps(data))

    return render_to_response(
        'ganeti/virtual_machine/edit_confirm.html',
        {
            'cluster': cluster,
            'form': form,
            'instance': vm,
            'instance_diff': instance_diff,
            'power': power,
        },
        context_instance=RequestContext(request),
    )

Example 190

Project: aemanager
Source File: views.py
View license
@csrf_exempt
@commit_on_success
def paypal_ipn(request):
    # send back the response to paypal
    data = dict(request.POST.items())
    args = {'cmd': '_notify-validate'}
    args.update(data)
    params = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in args.items()))
    paypal_response = urllib2.urlopen(settings.PAYPAL_URL + '/cgi-bin/webscr', params).read()

    # process the payment
    receiver_id = data['receiver_id']
    transaction_id = data['txn_id']
    payment_status = data['payment_status']
    payment_amount = data['mc_gross']
    payment_currency = data['mc_currency']
    fee = data['mc_fee']
    item_name = data['item_name']
    user_id = data['custom']
    user = get_object_or_404(User, pk=user_id)
    profile = user.get_profile()
    last_subscription = profile.get_last_subscription()

    subscription, created = Subscription.objects.get_or_create(transaction_id=transaction_id,
                                                               defaults={'owner': user,
                                                                         'state': SUBSCRIPTION_STATE_NOT_PAID,
                                                                         'expiration_date': profile.get_next_expiration_date(),
                                                                         'transaction_id': transaction_id,
                                                                         'error_message': ugettext('Not verified')})

    if paypal_response == 'VERIFIED':
        if receiver_id <> settings.PAYPAL_RECEIVER_ID:
            subscription.error_message = ugettext('Receiver is not as defined in settings. Spoofing ?')
        elif payment_status <> 'Completed':
            subscription.error_message = ugettext('Payment not completed')
        elif payment_amount <> settings.PAYPAL_APP_SUBSCRIPTION_AMOUNT:
            subscription.error_message = ugettext('Amount altered. Bad guy ?')
        elif payment_currency <> settings.PAYPAL_APP_SUBSCRIPTION_CURRENCY:
            subscription.error_message = ugettext('Amount altered. Bad guy ?')
        else:
            subscription.error_message = ugettext('Paid')
            subscription.state = SUBSCRIPTION_STATE_PAID

            # create an invoice for this payment
            # first, get the provider user
            provider = User.objects.get(email=settings.SERVICE_PROVIDER_EMAIL)
            if provider.get_profile().vat_number:
                payment_amount = Decimal(payment_amount) / Decimal('1.196')

            # look for a customer corresponding to user
            address, created = Address.objects.get_or_create(contact__email=user.email,
                                                             owner=provider,
                                                             defaults={'street': profile.address.street,
                                                                       'zipcode': profile.address.zipcode,
                                                                       'city': profile.address.city,
                                                                       'country': profile.address.country,
                                                                       'owner': provider})
            customer, created = Contact.objects.get_or_create(email=user.email,
                                                              defaults={'contact_type': CONTACT_TYPE_COMPANY,
                                                                        'name': '%s %s' % (user.first_name, user.last_name),
                                                                        'company_id': profile.company_id,
                                                                        'legal_form': 'Auto-entrepreneur',
                                                                        'email': user.email,
                                                                        'address': address,
                                                                        'owner': provider})
            # create a related project if needed
            # set it to finished to clear daily business
            project, created = Project.objects.get_or_create(state=PROJECT_STATE_FINISHED,
                                                             customer=customer,
                                                             name='Subscription %s - %s %s' % (Site.objects.get_current().name, user.first_name, user.last_name),
                                                             defaults={'state': PROJECT_STATE_FINISHED,
                                                                       'customer': customer,
                                                                       'name': 'Subscription %s - %s %s' % (Site.objects.get_current().name, user.first_name, user.last_name),
                                                                       'owner': provider})

            # create proposal for this subscription
            begin_date = datetime.date.today()
            if begin_date < last_subscription.expiration_date:
                begin_date = last_subscription.expiration_date

            proposal = Proposal.objects.create(project=project,
                                               reference='subscription%i%i%i' % (subscription.expiration_date.year,
                                                                                  subscription.expiration_date.month,
                                                                                  subscription.expiration_date.day),
                                               state=PROPOSAL_STATE_BALANCED,
                                               begin_date=begin_date,
                                               end_date=subscription.expiration_date,
                                               contract_content='',
                                               update_date=datetime.date.today(),
                                               expiration_date=None,
                                               owner=provider)

            unit_price = Decimal(settings.PAYPAL_APP_SUBSCRIPTION_AMOUNT)
            if provider.get_profile().vat_number:
                unit_price = Decimal(unit_price) / Decimal('1.196')

            proposal_row = ProposalRow.objects.create(proposal=proposal,
                                                      label=item_name,
                                                      category=ROW_CATEGORY_SERVICE,
                                                      quantity=1,
                                                      unit_price='%s' % unit_price,
                                                      owner=provider)

            # finally create invoice
            invoice = Invoice.objects.create(customer=customer,
                                             invoice_id=Invoice.objects.get_next_invoice_id(provider),
                                             state=INVOICE_STATE_PAID,
                                             amount=payment_amount,
                                             edition_date=datetime.date.today(),
                                             payment_date=datetime.date.today(),
                                             paid_date=datetime.date.today(),
                                             payment_type=PAYMENT_TYPE_BANK_CARD,
                                             execution_begin_date=begin_date,
                                             execution_end_date=subscription.expiration_date,
                                             penalty_date=None,
                                             penalty_rate=None,
                                             discount_conditions=None,
                                             owner=provider)

            invoice_row = InvoiceRow.objects.create(proposal=proposal,
                                                    invoice=invoice,
                                                    label=item_name,
                                                    category=ROW_CATEGORY_SERVICE,
                                                    quantity=1,
                                                    unit_price=payment_amount,
                                                    balance_payments=True,
                                                    vat_rate=VAT_RATES_19_6,
                                                    owner=provider)
            # create expense for paypal fee
            expense = Expense.objects.create(date=datetime.date.today(),
                                             reference=transaction_id,
                                             supplier='Paypal',
                                             amount=fee,
                                             payment_type=PAYMENT_TYPE_BANK_CARD,
                                             description='Commission paypal',
                                             owner=provider)

            # generate invoice in pdf
            response = HttpResponse(mimetype='application/pdf')
            invoice.to_pdf(provider, response)

            subject_template = loader.get_template('core/subscription_paid_email_subject.html')
            subject_context = {'site_name': Site.objects.get_current().name}
            subject = subject_template.render(Context(subject_context))
            body_template = loader.get_template('core/subscription_paid_email.html')
            body_context = {'site_name': Site.objects.get_current().name,
                            'expiration_date': subscription.expiration_date}
            body = body_template.render(Context(body_context))
            email = EmailMessage(subject=subject,
                                 body=body,
                                 to=[user.email])
            email.attach('facture_%i.pdf' % (invoice.invoice_id), response.content, 'application/pdf')
            email.send(fail_silently=(not settings.DEBUG))

        subscription.save()

    return render_to_response('core/paypal_ipn.html',
                              {'active': 'account',
                               'title': _('Subscribe')},
                              context_instance=RequestContext(request))

Example 191

Project: panda
Source File: views.py
View license
def dashboard(request):
    """
    Render HTML for dashboard/metrics view.
    """
    # Datasets
    dataset_count = Dataset.objects.all().count()

    datasets_without_descriptions = [(unquote(dataset['name']), dataset['slug']) for dataset in Dataset.objects.filter(description='').values('name', 'slug')]
    datasets_without_categories = [(unquote(dataset['name']), dataset['slug']) for dataset in Dataset.objects.filter(categories=None).values('name', 'slug')]

    # Users
    user_count = UserProxy.objects.all().count()
    activated_user_count = UserProxy.objects.filter(is_active=True).count()

    today = now().date()
    thirty_days_ago = today - datetime.timedelta(days=30)

    active_users = list(UserProxy.objects.raw('SELECT auth_user.*, count(panda_activitylog.id) AS activity_logs__count FROM auth_user LEFT JOIN panda_activitylog ON panda_activitylog.user_id = auth_user.id WHERE auth_user.is_active = True AND panda_activitylog.when > %s GROUP BY auth_user.id ORDER BY activity_logs__count DESC, auth_user.id ASC', [thirty_days_ago]))

    most_active_users = active_users[:10]

    if len(active_users) > 10:
        least_active_users = active_users[-10:]
        least_active_users.reverse()
    else:
        least_active_users = []

    inactive_users = UserProxy.objects.all() \
        .annotate(Count('activity_logs')) \
        .filter(activity_logs__count=0)

    _active_users_by_day = \
        list(ActivityLog.objects.filter(when__gt=thirty_days_ago) \
        .values('when') \
        .annotate(Count('id')) \
        .order_by('when'))

    dates = [thirty_days_ago + datetime.timedelta(days=x) for x in range(0, 31)]

    active_users_by_day = []

    for d in dates:
        if _active_users_by_day and _active_users_by_day[0]['when'] == d:
            _d = _active_users_by_day.pop(0)
            active_users_by_day.append(_d)
        else:
            active_users_by_day.append({ 'when': d, 'id__count': 0 })

    # Searches

    total_searches = SearchLog.objects.count()

    most_searched_datasets = [(unquote(dataset['name']), dataset['slug'], dataset['searches__count']) for dataset in \
        Dataset.objects.all() \
        .annotate(Count('searches')) \
        .filter(searches__count__gt=0) \
        .order_by('-searches__count') \
        .values('name', 'slug', 'searches__count')[:10]]

    _searches_by_day = \
        list(SearchLog.objects.filter(when__gt=thirty_days_ago) \
        .extra(select={ 'day': '"when"::date' }) \
        .values('day') \
        .annotate(Count('when')) \
        .order_by('day'))

    dates = [thirty_days_ago + datetime.timedelta(days=x) for x in range(0, 31)]

    searches_by_day = []

    for d in dates:
        if _searches_by_day and _searches_by_day[0]['day'] == d:
            _d = _searches_by_day.pop(0)
            searches_by_day.append(_d)
        else:
            searches_by_day.append({ 'day': d, 'when__count': 0 })

    # Disk space
    root_disk = os.stat('/').st_dev
    upload_disk = os.stat(settings.MEDIA_ROOT).st_dev
    indices_disk = os.stat(settings.SOLR_DIRECTORY).st_dev

    root_disk_total = utils.get_total_disk_space('/')
    root_disk_free = utils.get_free_disk_space('/')
    root_disk_percent_used = 100 - (float(root_disk_free) / root_disk_total * 100)

    if upload_disk != root_disk:    
        upload_disk_total = utils.get_total_disk_space(settings.MEDIA_ROOT)
        upload_disk_free = utils.get_free_disk_space(settings.MEDIA_ROOT)
        upload_disk_percent_used = 100 - (float(upload_disk_free) / upload_disk_total * 100)
    else:
        upload_disk_total = None
        upload_disk_free = None
        upload_disk_percent_used = None

    if indices_disk != root_disk:
        indices_disk_total = utils.get_total_disk_space(settings.SOLR_DIRECTORY)
        indices_disk_free = utils.get_free_disk_space(settings.SOLR_DIRECTORY)
        indices_disk_percent_used = 100 - (float(indices_disk_free) / indices_disk_total * 100)
    else:
        indices_disk_total = None
        indices_disk_free = None
        indices_disk_percent_used = None

    return render_to_response('dashboard.html', {
        'settings': settings,
        'dataset_count': dataset_count,
        'datasets_without_descriptions': datasets_without_descriptions,
        'datasets_without_categories': datasets_without_categories,
        'user_count': user_count,
        'activated_user_count': activated_user_count,
        'most_active_users': most_active_users,
        'least_active_users': least_active_users,
        'inactive_users': inactive_users,
        'active_users_by_day': active_users_by_day,
        'total_searches': total_searches,
        'most_searched_datasets': most_searched_datasets,
        'searches_by_day': searches_by_day,
        'root_disk_total': root_disk_total,
        'root_disk_free': root_disk_free,
        'root_disk_percent_used': root_disk_percent_used,
        'upload_disk_total': upload_disk_total,
        'upload_disk_free': upload_disk_free,
        'upload_disk_percent_used': upload_disk_percent_used,
        'indices_disk_total': indices_disk_total,
        'indices_disk_free': indices_disk_free,
        'indices_disk_percent_used': indices_disk_percent_used,
        'storage_documentation_url': 'http://panda.readthedocs.org/en/%s/storage.html' % settings.PANDA_VERSION
    })

Example 192

Project: django-admin-timeline
Source File: views.py
View license
@csrf_exempt
@never_cache
@staff_member_required
def log(request, template_name=TEMPLATE_NAME, \
        template_name_ajax=TEMPLATE_NAME_AJAX):
    """
    Get number of log entires. Serves both non-AJAX and AJAX driven requests.

    Since we have a breakdown of entries per day per entry and we have an AJAX
    driven infinite scroll and we want to avoid having duplicated date headers,
    we always pass a variable named "last_date" when making another request
    to our main AJAX-driven view. So... this is our case scenario:

    Initial timeline rendered as a normal HTML (non AJAX request) (from a list
    of log entries). We send date of last element as "last_date" to the context
    too, which will be used an an initial value for a global JavaScript
    variable. Later on that date will be used to send it to the AJAX driven
    view and used in rendering ("render_to_string" method). After we have
    rendered the HTML to send back, we get the last date of the last element
    and send it along with the HTML rendered to our view in JSON response.
    When receiving the JSON response, we update the above mentioned global
    JavaScript variable with the value given.

    :param request: django.http.HttpRequest
    :param template_name: str
    :param template_name_ajax: str
    :return: django.http.HttpResponse

    This view accepts the following POST variables (all optional).
    :param page: int - Page number to get.
    :param user_id: int - If set, used to filter the user by.
    :param last_date: str - Example value "2012-05-24".
    :param start_date: str - If set, used as a start date to filter the actions
        with. Example value "2012-05-24".
    :param end_date: str - If set, used as an end date to filter the actions
        with. Example value "2012-05-24".

    NOTE: If it gets too complicatd with filtering, we need to have forms to
    validate and process the POST data.
    """
    def _get_date_from_string(s):
        """
        Gets date from a string given.

        :param s: str - date in string format
        :return: datetime.datetime
        """
        try:
            return datetime.date(*map(lambda x: int(x), s.split("-")))
        except Exception as e:
            return ""

    try:
        page = int(request.POST.get('page', 1))
        if page < 1:
            page = 1
    except Exception as e:
        page = 1

    users = []
    content_types = []
    filter_form = None

    if 'POST' == request.method:
        post = dict(request.POST)
        if 'users[]' in post:
            post['users'] = post.pop('users[]')
        if 'content_types[]' in post:
            post['content_types'] = post.pop('content_types[]')

        filter_form = FilterForm(post)
        if filter_form.is_valid():
            users = filter_form.cleaned_data['users']
            content_types = filter_form.cleaned_data['content_types']
        else:
            pass # Anything to do here?
    else:
        filter_form = FilterForm()

    # Some kind of a pagination
    start = (page - 1) * NUMBER_OF_ENTRIES_PER_PAGE
    end = page * NUMBER_OF_ENTRIES_PER_PAGE

    # Getting admin log entires taking page number into consideration.
    log_entries = LogEntry.objects.all().select_related('content_type', 'user')

    start_date = _get_date_from_string(request.POST.get('start_date'))
    end_date = _get_date_from_string(request.POST.get('end_date'))

    if start_date:
        log_entries = log_entries.filter(action_time__gte=start_date) # TODO

    if end_date:
        log_entries = log_entries.filter(action_time__lte=end_date) # TODO

    # If users given, filtering by users
    if users:
        log_entries = log_entries.filter(user__id__in=users)

    # If content types given, filtering by content types
    if content_types:
        log_entries = log_entries.filter(content_type__id__in=content_types)

    # Applying limits / freezing the queryset
    log_entries = log_entries[start:end]

    if log_entries:
        last_date = date_format(
            log_entries[len(log_entries) - 1].action_time, "Y-m-d"
            )
    else:
        last_date = request.POST.get('last_date', None)

    # Using different template for AJAX driven requests
    if request.is_ajax():
        # Context to render the AJAX driven HTML with
        context = {
            'admin_log': log_entries,
            'number_of_entries_per_page': NUMBER_OF_ENTRIES_PER_PAGE,
            'page': page,
            'last_date': request.POST.get('last_date', None),
            'SINGLE_LOG_ENTRY_DATE_FORMAT': SINGLE_LOG_ENTRY_DATE_FORMAT,
            'LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT': \
                LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT
        }

        # Rendering HTML for an AJAX driven request
        html = render_to_string(
            template_name_ajax,
            context,
            context_instance=RequestContext(request)
        )

        # Context to send back to user in a JSON response
        context = {
            'html': html,
            'last_date': last_date,
            'success': 1 if len(log_entries) else 0
        }
        return HttpResponse(json.dumps(context))

    # Context for a non-AJAX request
    context = {
        'admin_log': log_entries,
        'number_of_entries_per_page': NUMBER_OF_ENTRIES_PER_PAGE,
        'page': page,
        'last_date': last_date,
        'start_date': date_format(start_date, "Y-m-d") if start_date else "",
        'end_date': date_format(end_date, "Y-m-d") if end_date else "",
        'users': [int(u) for u in users],
        'content_types': [int(ct) for ct in content_types],
        'filter_form': filter_form,
        'SINGLE_LOG_ENTRY_DATE_FORMAT': SINGLE_LOG_ENTRY_DATE_FORMAT,
        'LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT': \
            LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT,
        'title': _("Timeline") # For template breadcrumbs, etc.
    }

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

Example 193

Project: ocf
Source File: views.py
View license
def serve_rpc_request(request, url_name="root", **kwargs):
    '''
    This method handles rpc calls based on the content type of the request
    '''
    
    dispatcher = get_dispatcher(request.path, url_name)
    
    if request.method == "POST" and len(request.POST) > 0:
        # Handle POST request with RPC payload
        
        if LOG_REQUESTS_RESPONSES:
            logger.debug('\nIncoming request\n----------------')
            logger.debug('\n%s\n\n\n\n' % str(request.raw_post_data))
            
        if _is_xmlrpc_request(request):
            if RESTRICT_XML:
                raise Http404
            
            if not _check_request_permission(request, 'xml', url_name=url_name):
                return HttpResponseForbidden()
            
            resp = dispatcher.xmldispatch(request.raw_post_data,
                                          request=request, **kwargs)
            response_type = 'text/xml'
        else:
            if RESTRICT_JSON:
                raise Http404
            
            if not _check_request_permission(request, 'json',url_name=url_name):
                return HttpResponseForbidden()
            
            resp = dispatcher.jsondispatch(request.raw_post_data,
                                           request=request)
            response_type = 'application/json'
            
        if LOG_REQUESTS_RESPONSES:
            logger.debug('Outgoing %s request\n---------------------------' % response_type)
            logger.debug('\n%s\n\n\n\n' % resp)
        
        return HttpResponse(resp, response_type)
    elif request.method == 'OPTIONS':
        # Handle OPTIONS request for "preflighted" requests
        # see https://developer.mozilla.org/en/HTTP_access_control
        
        response = HttpResponse('', 'text/plain')
        
        origin = request.META.get('HTTP_ORIGIN', 'unknown origin')
        response['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
        response['Access-Control-Max-Age'] = 0
        response['Access-Control-Allow-Credentials'] = \
                        str(HTTP_ACCESS_CREDENTIALS).lower()
        response['Access-Control-Allow-Origin']= HTTP_ACCESS_ALLOW_ORIGIN
        
        response['Access-Control-Allow-Headers'] = \
                    request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS', '')
                    
        if LOG_REQUESTS_RESPONSES:
            logger.debug('Outgoing HTTP access response to: %s' %(origin))
                    
        return response
    else:
        # Handle GET request
        
        if RESTRICT_METHOD_SUMMARY:
            # hide the documentation by raising 404
            raise Http404
        
        # show documentation
        methods = dispatcher.list_methods()
        template_data = {
            'methods': methods,
            'url': request.path,
            
            # rpc4django version
            'version': version(),
            
            # restricts the ability to test the rpc server from the docs
            'restrict_rpctest': RESTRICT_RPCTEST,
        }
        return render_to_response('rpc4django/rpcmethod_summary.html', \
                                  template_data)

Example 194

Project: talk.org
Source File: comments.py
View license
def post_comment(request, extra_context=None, context_processors=None):
    """
    Post a comment

    Redirects to the `comments.comments.comment_was_posted` view upon success.

    Templates: `comment_preview`
    Context:
        comment
            the comment being posted
        comment_form
            the comment form
        options
            comment options
        target
            comment target
        hash
            security hash (must be included in a posted form to succesfully
            post a comment).
        rating_options
            comment ratings options
        ratings_optional
            are ratings optional?
        ratings_required
            are ratings required?
        rating_range
            range of ratings
        rating_choices
            choice of ratings
    """
    if extra_context is None: extra_context = {}
    if not request.POST:
        raise Http404, _("Only POSTs are allowed")
    try:
        options, target, security_hash = request.POST['options'], request.POST['target'], request.POST['gonzo']
    except KeyError:
        raise Http404, _("One or more of the required fields wasn't submitted")
    photo_options = request.POST.get('photo_options', '')
    rating_options = normalize_newlines(request.POST.get('rating_options', ''))
    if Comment.objects.get_security_hash(options, photo_options, rating_options, target) != security_hash:
        raise Http404, _("Somebody tampered with the comment form (security violation)")
    # Now we can be assured the data is valid.
    if rating_options:
        rating_range, rating_choices = Comment.objects.get_rating_options(base64.decodestring(rating_options))
    else:
        rating_range, rating_choices = [], []
    content_type_id, object_id = target.split(':') # target is something like '52:5157'
    try:
        obj = ContentType.objects.get(pk=content_type_id).get_object_for_this_type(pk=object_id)
    except ObjectDoesNotExist:
        raise Http404, _("The comment form had an invalid 'target' parameter -- the object ID was invalid")
    option_list = options.split(',') # options is something like 'pa,ra'
    new_data = request.POST.copy()
    new_data['content_type_id'] = content_type_id
    new_data['object_id'] = object_id
    new_data['ip_address'] = request.META.get('REMOTE_ADDR')
    new_data['is_public'] = IS_PUBLIC in option_list
    manipulator = PublicCommentManipulator(request.user,
        ratings_required=RATINGS_REQUIRED in option_list,
        ratings_range=rating_range,
        num_rating_choices=len(rating_choices))
    errors = manipulator.get_validation_errors(new_data)
    # If user gave correct username/password and wasn't already logged in, log them in
    # so they don't have to enter a username/password again.
    if manipulator.get_user() and not manipulator.get_user().is_authenticated() and 'password' in new_data and manipulator.get_user().check_password(new_data['password']):
        from django.contrib.auth import login
        login(request, manipulator.get_user())
    if errors or 'preview' in request.POST:
        class CommentFormWrapper(oldforms.FormWrapper):
            def __init__(self, manipulator, new_data, errors, rating_choices):
                oldforms.FormWrapper.__init__(self, manipulator, new_data, errors)
                self.rating_choices = rating_choices
            def ratings(self):
                field_list = [self['rating%d' % (i+1)] for i in range(len(rating_choices))]
                for i, f in enumerate(field_list):
                    f.choice = rating_choices[i]
                return field_list
        comment = errors and '' or manipulator.get_comment(new_data)
        comment_form = CommentFormWrapper(manipulator, new_data, errors, rating_choices)
        return render_to_response('comments/preview.html', {
            'comment': comment,
            'comment_form': comment_form,
            'options': options,
            'target': target,
            'hash': security_hash,
            'rating_options': rating_options,
            'ratings_optional': RATINGS_OPTIONAL in option_list,
            'ratings_required': RATINGS_REQUIRED in option_list,
            'rating_range': rating_range,
            'rating_choices': rating_choices,
        }, context_instance=RequestContext(request, extra_context, context_processors))
    elif 'post' in request.POST:
        # If the IP is banned, mail the admins, do NOT save the comment, and
        # serve up the "Thanks for posting" page as if the comment WAS posted.
        if request.META['REMOTE_ADDR'] in settings.BANNED_IPS:
            mail_admins("Banned IP attempted to post comment", smart_unicode(request.POST) + "\n\n" + str(request.META))
        else:
            manipulator.do_html2python(new_data)
            comment = manipulator.save(new_data)
        return HttpResponseRedirect("../posted/?c=%s:%s" % (content_type_id, object_id))
    else:
        raise Http404, _("The comment form didn't provide either 'preview' or 'post'")

Example 195

Project: dirigible-spreadsheet
Source File: views.py
View license
def register(request, success_url=None,
             form_class=RegistrationForm, profile_callback=None,
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register an account.
    
    Following successful registration, issue a redirect; by default,
    this will be whatever URL corresponds to the named URL pattern
    ``registration_complete``, which will be
    ``/accounts/register/complete/`` if using the included URLConf. To
    change this, point that named pattern at another URL, or pass your
    preferred URL as the keyword argument ``success_url``.
    
    By default, ``registration.forms.RegistrationForm`` will be used
    as the registration form; to change this, pass a different form
    class as the ``form_class`` keyword argument. The form class you
    specify must have a method ``save`` which will create and return
    the new ``User``, and that method must accept the keyword argument
    ``profile_callback`` (see below).
    
    To enable creation of a site-specific user profile object for the
    new user, pass a function which will create the profile object as
    the keyword argument ``profile_callback``. See
    ``RegistrationManager.create_inactive_user`` in the file
    ``models.py`` for details on how to write this function.
    
    By default, use the template
    ``registration/registration_form.html``; to change this, pass the
    name of a template as the keyword argument ``template_name``.
    
    **Required arguments**
    
    None.
    
    **Optional arguments**
    
    ``form_class``
        The form class to use for registration.
    
    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.
    
    ``profile_callback``
        A function which will be used to create a site-specific
        profile instance for the new ``User``.
    
    ``success_url``
        The URL to redirect to on successful registration.
    
    ``template_name``
        A custom template to use.
    
    **Context:**
    
    ``form``
        The registration form.
    
    Any extra variables supplied in the ``extra_context`` argument
    (see above).
    
    **Template:**
    
    registration/registration_form.html or ``template_name`` keyword
    argument.
    
    """
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = form.save(profile_callback=profile_callback)
            # success_url needs to be dynamically generated here; setting a
            # a default value using reverse() will cause circular-import
            # problems with the default URLConf for this application, which
            # imports this file.
            return HttpResponseRedirect(success_url or reverse('registration_complete'))
    else:
        form = form_class()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    return render_to_response(template_name,
                              { 'form': form },
                              context_instance=context)

Example 196

Project: virtmgr
Source File: views.py
View license
def pool(request, host_id, pool):

	if not request.user.is_authenticated():
		return HttpResponseRedirect('/')

	kvm_host = Host.objects.get(user=request.user.id, id=host_id)

	def add_error(msg, type_err):
		error_msg = Log(host_id=host_id, 
			            type=type_err, 
			            message=msg, 
			            user_id=request.user.id
			            )
		error_msg.save()

	def get_vms():
		try:
			vname = {}
			for id in conn.listDomainsID():
				id = int(id)
				dom = conn.lookupByID(id)
				vname[dom.name()] = dom.info()[0]
			for id in conn.listDefinedDomains():
				dom = conn.lookupByName(id)
				vname[dom.name()] = dom.info()[0]
			return vname
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_networks():
		try:
			networks = {}
			for name in conn.listNetworks():
				net = conn.networkLookupByName(name)
				status = net.isActive()
				networks[name] = status
			for name in conn.listDefinedNetworks():
				net = conn.networkLookupByName(name)
				status = net.isActive()
				networks[name] = status
			return networks
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def vm_conn():
		try:
			flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
			auth = [flags, creds, None]
			uri = 'qemu+tcp://' + kvm_host.ipaddr + '/system'
			conn = libvirt.openAuth(uri, auth, 0)
			return conn
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	if not kvm_host.login or not kvm_host.passwd:
		def creds(credentials, user_data):
			for credential in credentials:
				if credential[0] == libvirt.VIR_CRED_AUTHNAME:
					credential[4] = request.session['login_kvm']
					if len(credential[4]) == 0:
						credential[4] = credential[3]
				elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
					credential[4] = request.session['passwd_kvm']
				else:
					return -1
			return 0
	else:
		def creds(credentials, user_data):
			for credential in credentials:
				if credential[0] == libvirt.VIR_CRED_AUTHNAME:
					credential[4] = kvm_host.login
					if len(credential[4]) == 0:
						credential[4] = credential[3]
				elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
					credential[4] = kvm_host.passwd
				else:
					return -1
			return 0
			
	def get_conn_pool(pool):
		try:
			net = conn.networkLookupByName(pool)
			return net
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def pool_start():
		try:
			net.create()
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def pool_stop():
		try:
			net.destroy()
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def pool_delete():
		try:
			net.undefine()
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def net_set_autostart(pool):
		try:
			net = conn.networkLookupByName(pool)
			net.setAutostart(1)
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_net_info(get):
		try:
			if get == "bridge":
				return net.bridgeName()
			elif get == "status":
				return net.isActive()
			elif get == "start":
				return net.autostart()
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_ipv4_net():
		try:
			net = conn.networkLookupByName(pool)
			xml = net.XMLDesc(0)
			addrStr = util.get_xml_path(xml, "/network/ip/@address")
			netmaskStr = util.get_xml_path(xml, "/network/ip/@netmask")

			netmask = IP(netmaskStr)
			gateway = IP(addrStr)

			network = IP(gateway.int() & netmask.int())
			return IP(str(network) + "/" + netmaskStr)
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_ipv4_dhcp_range():
		try:
			net = conn.networkLookupByName(pool)
			xml = net.XMLDesc(0)
			dhcpstart = util.get_xml_path(xml, "/network/ip/dhcp/range[1]/@start")
			dhcpend = util.get_xml_path(xml, "/network/ip/dhcp/range[1]/@end")
			if not dhcpstart or not dhcpend:
				return None
			
			return [IP(dhcpstart), IP(dhcpend)]
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_ipv4_forward():
		try:
			xml = net.XMLDesc(0)
			fw = util.get_xml_path(xml, "/network/forward/@mode")
			forwardDev = util.get_xml_path(xml, "/network/forward/@dev")
			return [fw, forwardDev]
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def create_net_pool(name_pool, forward, ipaddr, netmask, dhcp, s_dhcp, e_dhcp):
		try:
			xml = """
				<network>
					<name>%s</name>""" % (name_pool)

			if forward == "nat" or "route":
				xml += """<forward mode='%s'/>""" % (forward)

			xml += """<bridge stp='on' delay='0' />
						<ip address='%s' netmask='%s'>""" % (gw_ipaddr, netmask)

			if dhcp == "yes":
				xml += """<dhcp>
							<range start='%s' end='%s' />
						</dhcp>""" % (s_dhcp, e_dhcp)
					
			xml += """</ip>
				</network>"""
			conn.networkDefineXML(xml)
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	conn = vm_conn()

	if conn == None:
		return HttpResponseRedirect('/overview/%s/' % (host_id))

	pools = get_networks()
	all_vm = get_vms()
	errors = []

	if pool != 'new_net_pool':
		net = get_conn_pool(pool)
		bridge = get_net_info('bridge')
		status = get_net_info('status')
		if status == 1:
			start = get_net_info('start')
			network = get_ipv4_net()
			dhcprange = get_ipv4_dhcp_range()
			netmode = get_ipv4_forward()

	if request.method == 'POST':
		if request.POST.get('new_net_pool',''):
			name_pool = request.POST.get('name_pool','')
			net_addr = request.POST.get('net_addr','')
			forward = request.POST.get('forward','')
			dhcp = request.POST.get('dhcp','')
			simbol = re.search('[^a-zA-Z0-9\_]+', name_pool)
			if len(name_pool) > 20:
				msg = _('The name of the network pool must not exceed 20 characters')
				errors.append(msg)
			if simbol:
				msg = _('The name of the network pool must not contain any characters and Russian characters')
				errors.append(msg)
			if not name_pool:
				msg = _('Enter the name of the pool')
				errors.append(msg)
			if not net_addr:
				msg = _('Enter the IP subnet')
				errors.append(msg)
			try:
				netmask = IP(net_addr).strNetmask()
				ipaddr = IP(net_addr)
				gw_ipaddr = ipaddr[1].strNormal()
				start_dhcp = ipaddr[2].strNormal()
				end_dhcp = ipaddr[254].strNormal()
			except:
				msg = _('IP subnet must be 192.168.1.0/24 or 192.168.1.0/26')
				errors.append(msg)
			if errors:
				return render_to_response('network.html', locals())
			if not errors:
				if create_net_pool(name_pool, forward, gw_ipaddr, netmask, dhcp, start_dhcp, end_dhcp) is "error":
					msg = _('Such a pool already exists')
					errors.append(msg)
				if not errors:
					net_set_autostart(name_pool)
					net = get_conn_pool(name_pool)
					if pool_start() is "error":
						msg = _('Pool is created, but when I run the pool fails, you may specify an existing network')
						errors.append(msg)
					else:
						msg = _('Creating a network pool: ') 
						msg = msg + name_pool
						add_error(msg, 'user')
						return HttpResponseRedirect('/network/%s/%s/' % (host_id, name_pool))
					if errors:
						return render_to_response('network.html', locals())
		if request.POST.get('stop_pool',''):
			msg = _('Stop network pool: ')
			msg = msg + pool
			pool_stop()
			add_error(msg, 'user')
		if request.POST.get('start_pool',''):
			msg = _('Start network pool: ')
			msg = msg + pool
			pool_start()
			add_error(msg, 'user')
		if request.POST.get('del_pool',''):
			msg = _('Delete network pool: ')
			msg = msg + pool
			pool_delete()
			add_error(msg, 'user')
			return HttpResponseRedirect('/network/%s/' % (host_id))
		return HttpResponseRedirect('/network/%s/%s/' % (host_id, pool))

	conn.close()

	return render_to_response('network.html', locals())

Example 197

Project: classic.rhizome.org
Source File: views.py
View license
@login_required  
def edit(request, type, id):
    context = RequestContext(request)
    username = request.user.get_profile()       
        
    #CHECK THE TYPE, GRAB OBJECT OR CATCH MISSING INFO
    if type == 'opportunities':
        announcement = get_object_or_404(Opportunity, id=id, is_spam=False)
        announcement_form = OpportunityForm(
                                request.POST or None, 
                                request.FILES or None, 
                                instance=announcement, 
                                initial={'username':username}
                            )
    elif type == 'jobs':
        announcement = get_object_or_404(Job, id=id, is_spam=False)
        announcement_form = JobForm(
                                request.POST or None, 
                                request.FILES or None, 
                                instance=announcement,  
                                initial={'username':username}
                                )
    elif type == 'events':
        announcement = get_object_or_404(Event, id=id, is_spam=False)
        announcement_form = EventForm(
                                request.POST or None, 
                                request.FILES or None, 
                                instance=announcement, 
                                initial={'username':username}
                            )
    else:
        raise Http404
    
    if not announcement.can_edit():
        # can only edit if announcement less than 2 wks old...    
        return HttpResponseRedirect(reverse('announce_index'))  
    else:
        # MAKE SURE THE USER OWNS THE ANNOUNCEMENT
        if request.user != announcement.user:
            return HttpResponseRedirect(reverse('announce_index'))  
        else:
            # HANDLE THE POST
            if request.method == 'POST':
            
                if request.POST.get("form-type") == "opportunity-form":
                    announcement_form = OpportunityForm(
                                            request.POST, 
                                            request.FILES or None, 
                                            instance=announcement, 
                                            initial={'username':username}
                                        )
                if request.POST.get("form-type") == "job-form":
                    announcement_form = JobForm(
                                            request.POST, 
                                            request.FILES or None, 
                                            instance=announcement, 
                                            initial={'username':username}
                                        )
                if request.POST.get("form-type") == "event-form":  
                    announcement_form = EventForm(
                                            request.POST, 
                                            request.FILES or None, 
                                            instance=announcement, 
                                            initial={'username':username}
                                            )
           
                if announcement_form.is_valid():
                    announcement = announcement_form.save(commit=False)
                    announcement.user_id = request.user.id
                    announcement.ip_address = request.META["REMOTE_ADDR"]
                    
                    if request.POST.get("delete_image"):
                        if announcement.image:
                            import os
                            if os.path.exists(announcement.image.path):
                                os.remove(announcement.image.path)
                        announcement.image = None
                    
                    #save now so can create thumbanail with id in title
                    announcement.save() 
                    
                    if announcement.image and not announcement.thumbnail:
                        announcement.thumbnail = create_thumbnail(announcement.image)
                        announcement.save()           
                    
                    ####
                    # if announcement is not yet published
                    ####
                    if request.POST.get("status") == "preview":
                        announcement.status = False
                        announcement.save()
                        return HttpResponseRedirect(reverse(preview, kwargs={'type':type, 'id':announcement.id}))                    
                        
                    if request.POST.get("status") == "publish":

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

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

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

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

Example 198

Project: splunk-webframework
Source File: comments.py
View license
@csrf_protect
@require_POST
def post_comment(request, next=None, using=None):
    """
    Post a comment.

    HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
    errors a preview template, ``comments/preview.html``, will be rendered.
    """
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.get_username()
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest("Missing content_type or object_pk field.")
    try:
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.using(using).get(pk=object_pk)
    except TypeError:
        return CommentPostBadRequest(
            "Invalid content_type value: %r" % escape(ctype))
    except AttributeError:
        return CommentPostBadRequest(
            "The given content-type %r does not resolve to a valid model." % \
                escape(ctype))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type %r and object PK %r exists." % \
                (escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError) as e:
        return CommentPostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
                (escape(ctype), escape(object_pk), e.__class__.__name__))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Construct the comment form
    form = comments.get_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: %s" % \
                escape(str(form.security_errors())))

    # If there are errors or if we requested a preview show the comment
    if form.errors or preview:
        template_list = [
            # These first two exist for purely historical reasons.
            # Django v1.0 and v1.1 allowed the underscore format for
            # preview templates, so we have to preserve that format.
            "comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.module_name),
            "comments/%s_preview.html" % model._meta.app_label,
            # Now the usual directory based template hierarchy.
            "comments/%s/%s/preview.html" % (model._meta.app_label, model._meta.module_name),
            "comments/%s/preview.html" % model._meta.app_label,
            "comments/preview.html",
        ]
        return render_to_response(
            template_list, {
                "comment": form.data.get("comment", ""),
                "form": form,
                "next": data.get("next", next),
            },
            RequestContext(request, {})
        )

    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(
        sender=comment.__class__,
        comment=comment,
        request=request
    )

    for (receiver, response) in responses:
        if response == False:
            return CommentPostBadRequest(
                "comment_will_be_posted receiver %r killed the comment" % receiver.__name__)

    # Save the comment and signal that it was saved
    comment.save()
    signals.comment_was_posted.send(
        sender=comment.__class__,
        comment=comment,
        request=request
    )

    return next_redirect(request, fallback=next or 'comments-comment-done',
        c=comment._get_pk_val())

Example 199

Project: cdr-stats
Source File: views.py
View license
@permission_required('user_profile.overview', login_url='/')
@check_user_detail('accountcode')
@login_required
def cdr_overview(request):
    """CDR graph by hourly/daily/monthly basis

    **Attributes**:

        * ``template`` - cdr/overview.html
        * ``form`` - CdrOverviewForm

    **Logic Description**:

        Get Call records from Postgresql table and build
        all monthly, daily, hourly analytics
    """
    # initialize variables
    hourly_charttype = "lineWithFocusChart"
    daily_charttype = "lineWithFocusChart"
    hourly_chartdata = {'x': []}
    daily_chartdata = {'x': []}
    metric = 'nbcalls'  # Default metric

    action = 'tabs-1'
    tday = datetime.today()
    switch_id = 0
    # assign initial value in form fields
    form = CdrOverviewForm(request.POST or None,
                           initial={'from_date': tday.strftime('%Y-%m-%d 00:00'),
                                    'to_date': tday.strftime('%Y-%m-%d 23:55'),
                                    'switch_id': switch_id})
    start_date = trunc_date_start(tday)
    end_date = trunc_date_end(tday)
    if form.is_valid():
        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = trunc_date_start(from_date)
        end_date = trunc_date_end(to_date)
        switch_id = getvar(request, 'switch_id')
        metric = getvar(request, 'metric')

    # get the number of hour that diff the date
    delta = end_date - start_date
    hour_diff = abs(divmod(delta.days * 86400 + delta.seconds, 60)[0]) / 60
    if hour_diff <= 72:
        display_chart = 'hourly'
    else:
        display_chart = 'daily'

    # check metric is valid
    if metric not in ['nbcalls', 'duration', 'billsec', 'buy_cost', 'sell_cost']:
        metric = 'nbcalls'

    extra_serie = {
        "tooltip": {"y_start": "", "y_end": " " + metric},
        "date_format": "%d %b %y %H:%M%p"
    }

    if display_chart == 'hourly':
        hourly_data = get_report_cdr_per_switch(request.user, 'hour', start_date, end_date, switch_id)

        for switch in hourly_data[metric]["columns"]:
            hourly_chartdata['x'] = hourly_data[metric]["x_timestamp"]
            hourly_chartdata['name' + str(switch)] = get_switch_ip_addr(switch)
            hourly_chartdata['y' + str(switch)] = hourly_data[metric]["values"][str(switch)]
            hourly_chartdata['extra' + str(switch)] = extra_serie

        total_calls = hourly_data["nbcalls"]["total"]
        total_duration = hourly_data["duration"]["total"]
        total_billsec = hourly_data["billsec"]["total"]
        total_buy_cost = hourly_data["buy_cost"]["total"]
        total_sell_cost = hourly_data["sell_cost"]["total"]

    elif display_chart == 'daily':
        daily_data = get_report_cdr_per_switch(request.user, 'day', start_date, end_date, switch_id)

        for switch in daily_data[metric]["columns"]:
            daily_chartdata['x'] = daily_data[metric]["x_timestamp"]
            daily_chartdata['name' + str(switch)] = get_switch_ip_addr(switch)
            daily_chartdata['y' + str(switch)] = daily_data[metric]["values"][str(switch)]
            daily_chartdata['extra' + str(switch)] = extra_serie

        total_calls = daily_data["nbcalls"]["total"]
        total_duration = daily_data["duration"]["total"]
        total_billsec = daily_data["billsec"]["total"]
        total_buy_cost = daily_data["buy_cost"]["total"]
        total_sell_cost = daily_data["sell_cost"]["total"]

    # Calculate the Average Time of Call
    metric_aggr = calculate_act_acd(total_calls, total_duration)

    # Get top 10 of country calls
    country_data = custom_sql_aggr_top_country(request.user, switch_id, 10, start_date, end_date)

    variables = {
        'action': action,
        'form': form,
        'display_chart': display_chart,
        'start_date': start_date,
        'end_date': end_date,
        'metric': metric,
        'hourly_chartdata': hourly_chartdata,
        'hourly_charttype': hourly_charttype,
        'hourly_chartcontainer': 'hourly_container',
        'hourly_extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %y %H%p',
            'tag_script_js': True,
            'jquery_on_ready': True,
        },
        'daily_chartdata': daily_chartdata,
        'daily_charttype': daily_charttype,
        'daily_chartcontainer': 'daily_container',
        'daily_extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %Y',
            'tag_script_js': True,
            'jquery_on_ready': True,
        },
        'total_calls': total_calls,
        'total_duration': total_duration,
        'total_billsec': total_billsec,
        'total_buy_cost': total_buy_cost,
        'total_sell_cost': total_sell_cost,
        'metric_aggr': metric_aggr,
        'country_data': country_data,
    }
    return render_to_response('cdr/overview.html', variables, context_instance=RequestContext(request))

Example 200

Project: hunch-gift-app
Source File: comments.py
View license
@csrf_protect
@require_POST
def post_comment(request, next=None, using=None):
    """
    Post a comment.

    HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
    errors a preview template, ``comments/preview.html``, will be rendered.
    """
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Check to see if the POST data overrides the view's next argument.
    next = data.get("next", next)

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest("Missing content_type or object_pk field.")
    try:
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.using(using).get(pk=object_pk)
    except TypeError:
        return CommentPostBadRequest(
            "Invalid content_type value: %r" % escape(ctype))
    except AttributeError:
        return CommentPostBadRequest(
            "The given content-type %r does not resolve to a valid model." % \
                escape(ctype))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type %r and object PK %r exists." % \
                (escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError), e:
        return CommentPostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
                (escape(ctype), escape(object_pk), e.__class__.__name__))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Construct the comment form
    form = comments.get_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: %s" % \
                escape(str(form.security_errors())))

    # If there are errors or if we requested a preview show the comment
    if form.errors or preview:
        template_list = [
            # These first two exist for purely historical reasons.
            # Django v1.0 and v1.1 allowed the underscore format for
            # preview templates, so we have to preserve that format.
            "comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.module_name),
            "comments/%s_preview.html" % model._meta.app_label,
            # Now the usual directory based template heirarchy.
            "comments/%s/%s/preview.html" % (model._meta.app_label, model._meta.module_name),
            "comments/%s/preview.html" % model._meta.app_label,
            "comments/preview.html",
        ]
        return render_to_response(
            template_list, {
                "comment" : form.data.get("comment", ""),
                "form" : form,
                "next": next,
            },
            RequestContext(request, {})
        )

    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )

    for (receiver, response) in responses:
        if response == False:
            return CommentPostBadRequest(
                "comment_will_be_posted receiver %r killed the comment" % receiver.__name__)

    # Save the comment and signal that it was saved
    comment.save()
    signals.comment_was_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )

    return next_redirect(data, next, comment_done, c=comment._get_pk_val())