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 51

Project: colab
Source File: views.py
View license
def issues(request, mine=False, template_name="issues/issues.html"):
    authenticated = request.user.is_authenticated()
    
    if authenticated and mine:
        issues = Issue.objects.filter(contributor_users=request.user)
    else:
        issues = Issue.objects.filter(private=False)
    
    search_terms = request.GET.get('search', '')
    if search_terms:
        issues = (issues.filter(title__icontains=search_terms) |
            issues.filter(description__icontains=search_terms))
    
    # Additional filtering
    sandbox = request.GET.get('sandbox', None)
    model_project = request.GET.get('model_project', None)
    discipline = request.GET.get('discipline', None)
    the_discipline = None
    tag = request.GET.get('tag', None)
    the_tag = None
    if not sandbox:
        issues = issues.filter(sandbox=False)
    if model_project:
        issues = issues.filter(model_project=True)
    if discipline:
        try:
            the_discipline = Discipline.objects.get(slug=discipline) # make sure the discpline exists
            issues = issues.filter(disciplines=the_discipline)
        except Discipline.DoesNotExist:
            messages.add_message(request, messages.ERROR, _("That discipline does not exist."))
    if tag:
        try:
            the_tag = Tag.objects.get(id=tag) # make sure the tag exists
            issues = TaggedItem.objects.get_by_model(issues, the_tag)
        except Tag.DoesNotExist:
            messages.add_message(request, messages.ERROR, _("That tag does not exist."))
    
    # get filter querysets
    if the_discipline:
        discipline_filters = the_discipline.get_children()[:10]
    else:
        discipline_filters = Discipline.tree.root_nodes()[:10]
    if the_tag:
        tag_filters = Tag.objects.related_for_model(the_tag, Issue)[:10]
    else:
        tag_filters = Tag.objects.usage_for_model(Issue)[:10]
    
    # Figure out sorting to replace the title
    list_title = ''
    if mine:
        list_title += 'My '
    
    sort = request.GET.get('sort', 'created')
    direction = request.GET.get('dir', 'desc')
    
    if sort == 'created' and direction == 'desc':
        list_title += 'Newest Issues'
        issues = issues.order_by('-created')
    if sort == 'created' and direction == 'asc':
        list_title += 'Oldest Issues'
        issues = issues.order_by('created')
    if sort == 'yeas' and direction == 'desc':
        list_title += 'Most Liked Issues'
        issues = issues.order_by('-yeas')
    if sort == 'yeas' and direction == 'asc':
        list_title += 'Least Liked Issues'
        issues = issues.order_by('yeas')
    if sort == 'nays' and direction == 'desc':
        list_title += 'Most Disliked Issues'
        issues = issues.order_by('-nays')
    if sort == 'nays' and direction == 'asc':
        list_title += 'Least Disliked Issues'
        issues = issues.order_by('nays')
    
    # Paginate the list
    paginator = Paginator(issues, 20) # Show 20 issues per page
    
    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page is out of range, deliver last page of results.
    try:
        issues = paginator.page(page)
    except (EmptyPage, InvalidPage):
        issues = paginator.page(paginator.num_pages)
    
    return render_to_response(template_name, {
        'issues': issues,
        'mine': mine,
        'search_terms': search_terms, 'the_discipline': the_discipline,
        'discipline_filters': discipline_filters, 'tag_filters': tag_filters,
        'the_tag': the_tag, 'sandbox': sandbox, 'model_project': model_project,
        'sort': sort, 'direction': direction,
        'list_title': list_title,
    }, context_instance=RequestContext(request))

Example 52

Project: django-templatesadmin
Source File: views.py
View license
@never_cache
@user_passes_test(lambda u: user_in_templatesadmin_group(u))
@login_required
def modify(request,
           path,
           template_name='templatesadmin/edit.html',
           base_form=TemplateForm,
           available_template_dirs=TEMPLATESADMIN_TEMPLATE_DIRS):

    template_path = _fixpath(path)

    # Check if file is within template-dirs
    if not any([template_path.startswith(templatedir) for templatedir in available_template_dirs]):
        request.user.message_set.create(message=_('Sorry, that file is not available for editing.'))
        return HttpResponseRedirect(reverse('templatesadmin-overview'))

    if request.method == 'POST':
        formclass = base_form
        for hook in TEMPLATESADMIN_EDITHOOKS:
            formclass.base_fields.update(hook.contribute_to_form(template_path))

        form = formclass(request.POST)
        if form.is_valid():
            content = form.cleaned_data['content']

            try:
                for hook in TEMPLATESADMIN_EDITHOOKS:
                    pre_save_notice = hook.pre_save(request, form, template_path)
                    if pre_save_notice:
                        request.user.message_set.create(message=pre_save_notice)
            except TemplatesAdminException, e:
                request.user.message_set.create(message=e.message)
                return HttpResponseRedirect(request.build_absolute_uri())

            # Save the template
            try:
                f = open(template_path, 'r')
                file_content = f.read()
                f.close()

                # browser tend to strip newlines from <textarea/>s before
                # HTTP-POSTing: re-insert them if neccessary

                # content is in dos-style lineending, will be converted in next step
                if (file_content[-1] == '\n' or file_content[:-2] == '\r\n') \
                   and content[:-2] != '\r\n':
                    content = u"%s\r\n" % content

                # Template is saved in unix-style, save in unix style.
                if None == search("\r\n", file_content):
                    content = content.replace("\r\n", "\n")

                f = codecs.open(template_path, 'w', 'utf-8')
                f.write(content)
                f.close()
            except IOError, e:
                request.user.message_set.create(
                    message=_('Template "%(path)s" has not been saved! Reason: %(errormsg)s' % {
                        'path': path,
                        'errormsg': e
                    })
                )
                return HttpResponseRedirect(request.build_absolute_uri())

            try:
                for hook in TEMPLATESADMIN_EDITHOOKS:
                    post_save_notice = hook.post_save(request, form, template_path)
                    if post_save_notice:
                        request.user.message_set.create(message=post_save_notice)
            except TemplatesAdminException, e:
                request.user.message_set.create(message=e.message)
                return HttpResponseRedirect(request.build_absolute_uri())

            request.user.message_set.create(
                message=_('Template "%s" was saved successfully.' % path)
            )
            return HttpResponseRedirect(reverse('templatesadmin-overview'))
    else:
        template_file = codecs.open(template_path, 'r', 'utf-8').read()

        formclass = TemplateForm
        for hook in TEMPLATESADMIN_EDITHOOKS:
            formclass.base_fields.update(hook.contribute_to_form(template_path))

        form = formclass(
            initial={'content': template_file}
        )

    template_context = {
        'messages': request.user.get_and_delete_messages(),
        'form': form,
        'short_path': path,
        'template_path': path,
        'template_writeable': os.access(template_path, os.W_OK),
        'ADMIN_MEDIA_PREFIX': settings.ADMIN_MEDIA_PREFIX,
    }

    return render_to_response(template_name, template_context,
                              RequestContext(request))

Example 53

Project: CityCircles
Source File: views.py
View license
def test2(request, from_zl=DEFAULT_ZOOM, to_zl=DEFAULT_ZOOM, center_x=WIDTH/2, center_y=HEIGHT/2, from_origin_x=DEFAULT_VIEWALBE_ORIGIN_LL_X, from_origin_y = DEFAULT_VIEWALBE_ORIGIN_LL_Y):
    dct_return = {
        "points": "", #json encoded list of points to draw
        "tiles": "", #json encoded list of tiles
        "world_origin_x": from_origin_x,  #default to the from origin
        "world_origin_y": from_origin_y,
        "curr_zl": to_zl,
        "nxt_zl": False
    }
    
    ZOOM_RATIOS = {
    10: [1,1],
    12: [255.92568888889946/1023.70276,
         256.0/1024.0],
    15: [255.92568888889946/8189.62204,
         256.0/8192.0]
    }
    
    ZOOM_SCREEN_SIZES = {
        10: [WIDTH, HEIGHT],
        12: [WIDTH / ZOOM_RATIOS[12][0], HEIGHT / ZOOM_RATIOS[12][1]],
        15: [WIDTH / ZOOM_RATIOS[15][0], HEIGHT / ZOOM_RATIOS[15][1]],
    }
    
    ZOOM_WORLD_ORIGINS = {
        10: [49358.074311111101,
             157103.0],
        12: [197432.2972444444,
             627389.53504310793],
        15: [1579458.3779555552,
             5019116.2803448634]
    }
    
    #import rpdb2; rpdb2.start_embedded_debugger("password")
    from_zl = int(from_zl)
    to_zl = int(to_zl)
    center_x = int(center_x)
    center_y = HEIGHT - int(center_y)
    from_origin_x = int(from_origin_x)
    from_origin_y = int(from_origin_y)
    
    if ZOOMS.index(to_zl) == (len(ZOOMS) - 1):
        dct_return["nxt_zl"] = to_zl
    else:
        dct_return["nxt_zl"] = ZOOMS[ZOOMS.index(to_zl) + 1]    
    
    import rpdb2; rpdb2.start_embedded_debugger("password")
    #CONVERT CENTER_X, CENTER_Y TO METERS AT FROM ZOOM LEVEL
    from_zl = int(from_zl)
    #ll_m_x, ll_m_y = mercator.LatLonToMeters(MAP_LL_LAT, MAP_LL_LONG)
    #this is the x,y values for the world map origin at the from zoom level
    #ll_x, ll_y = mercator.MetersToPixels(ll_m_x, ll_m_y, from_zl)
    ll_x = from_origin_x
    ll_y = from_origin_y
    
    #center_x, center_y origin at the from zoom level
    c_w_x = ll_x + center_x
    c_w_y = ll_y + center_y
    
    #now make this meters
    c_w_m_x, c_w_m_y = mercator.PixelsToMeters(c_w_x, c_w_y, from_zl)
    
    #NOW MAKE THIS CENTER_X, CENTER_Y AT THE NEW ZOOM LEVEL
    existing_n_c_w_x, existing_n_c_w_y = mercator.MetersToPixels(c_w_m_x, c_w_m_y, to_zl)
    
    n_c_x = ZOOM_SCREEN_SIZES[to_zl][0] * (center_x / ZOOM_SCREEN_SIZES[from_zl][0])
    n_c_y = ZOOM_SCREEN_SIZES[to_zl][1] * (center_y / ZOOM_SCREEN_SIZES[from_zl][1])
    
    n_c_w_x = ZOOM_WORLD_ORIGINS[to_zl][0] + n_c_x
    n_c_w_y = ZOOM_WORLD_ORIGINS[to_zl][1] + n_c_y
    
    #CALCULATE THE NEW ZOOM LVLS ORIGIN IN THE WORLD
    n_ll_w_x = round(n_c_w_x - (WIDTH / 2)) #new lower left world x
    n_ll_w_y = round(n_c_w_y - (HEIGHT / 2)) # " y
    
    dct_return["world_origin_x"] = n_ll_w_x
    dct_return["world_origin_y"] = n_ll_w_y
    
    n_ur_w_x = n_ll_w_x + WIDTH
    n_ur_w_y = n_ll_w_y + HEIGHT
    
    li_tiles = []
    
    pnt_ll_w = pntsandrects.Point(n_ll_w_x, n_ll_w_y)
    pnt_ur_w = pntsandrects.Point(n_ur_w_x, n_ur_w_y)
    viewable_rect = pntsandrects.Rect(pnt_ll_w, pnt_ur_w)
    
    #MAKE A LIST OF TILES AT THIS ZOOM LEVEL THAT TOUCH THE VIEWABLE AREA
    for model_tile in Tile.objects.filter(level=to_zl):
        import rpdb2; rpdb2.start_embedded_debugger("password")
        #CONVERT THE TILES X,Y VALUES TO WORLD PIXEL X,Y AT THIS NEW ZOOM LEVEL
        #THE MAP TILES X,Y VALUES ARE IN RELATION TO THE MAX BOUNDS OF THE MAP, NOT VIEWABLE AREA
        #import rpdb2; rpdb2.start_embedded_debugger("password")
        #ll_m_x, ll_m_y = mercator.LatLonToMeters(MAP_LL_LAT, MAP_LL_LONG)
        #atile_origin_x, atile_origin_y = mercator.MetersToPixels(ll_m_x, ll_m_y, to_zl)
        
        tile_origin_x, tile_origin_y = ZOOM_WORLD_ORIGINS[to_zl]
        
        n_tile_ll_w_x = round(tile_origin_x + model_tile.ll_x)
        n_tile_ll_w_y = round(tile_origin_y + model_tile.ll_y)
        
        tile_pnt_ll_w = pntsandrects.Point(n_tile_ll_w_x, n_tile_ll_w_y)
        tile_pnt_ur_w = pntsandrects.Point(n_tile_ll_w_x + model_tile.size_x, n_tile_ll_w_y + model_tile.size_y)
        tile_rect = pntsandrects.Rect(tile_pnt_ll_w, tile_pnt_ur_w)
        if viewable_rect.overlaps(tile_rect):
            li_tiles.append(["/" + model_tile.fl_name, n_tile_ll_w_x - n_ll_w_x, HEIGHT - (TILE_SIZE + (n_tile_ll_w_y - n_ll_w_y)) ])
            
    #NOW THE LIGHTRAIL LINES
    li_shapes = []
            
    dct_return["tiles"] = simplejson.dumps(li_tiles)
    dct_return["points"] = simplejson.dumps(li_shapes)
    return render_to_response('test.html', dct_return)

Example 54

Project: classic.rhizome.org
Source File: views.py
View license
@login_required
def edit_profile(request): 
    context = RequestContext(request)
    rhizomeuser = request.user.get_profile()
    
    initial_list_data = [l.listid for l in Member.objects.filter(user=rhizomeuser, deleted = 0)]
    
    personal_info_form = EditPersonalInfoForm(instance=rhizomeuser)
    account_info_form = EditAccountInfoForm(instance=rhizomeuser)
    bio_form = EditBioForm(instance=rhizomeuser)
    add_info_form = EditAdditionalInfoForm(instance=rhizomeuser)
   
    try:
        address = rhizomeuser.address('billing')
        address_form = UserBillingAddressForm(instance=address)
    except:
        address_form = UserBillingAddressForm()
    
    set_password_form = SetPasswordForm(rhizomeuser)
    manage_email_form = ManageForm(request.POST or None, initial={'mailinglists':initial_list_data})
    ip_address = request.META.get('REMOTE_ADDR', 'unknown')
    updated = ''
    
    if request.method == 'POST': 
        response = ''           
        if request.POST['form'] == "personal_info":
            
            personal_info_form = EditPersonalInfoForm(request.POST or None, 
                    instance=rhizomeuser and RhizomeUser.objects.get(id=rhizomeuser.id))
            
            if personal_info_form.is_valid():
                rhizomeuser = personal_info_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
                
        if request.POST['form'] == "address_form":
            try:
                address_form = UserBillingAddressForm(request.POST or None, instance=address)        
            except:
                address_form = UserBillingAddressForm(request.POST or None)
            if address_form.is_valid():
                address_form.save(rhizomeuser)
                updated = "pass"
            else:
                updated = "fail" 
                          
        if request.POST['form'] == "bio":
            bio_form = EditBioForm(request.POST or None, 
                    instance=rhizomeuser and RhizomeUser.objects.get(id=rhizomeuser.id))        
            if bio_form.is_valid():
                rhizomeuser = bio_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
                
        if request.POST['form'] == "account_info":
            account_info_form = EditAccountInfoForm(request.POST or None, request.FILES or None, 
                    instance=rhizomeuser and RhizomeUser.objects.get(id=rhizomeuser.id))
            if account_info_form.is_valid():
                rhizomeuser = account_info_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
                        
        if request.POST['form'] == "set_password":
            set_password_form = SetPasswordForm(rhizomeuser,request.POST)
            if set_password_form.is_valid():
                rhizomeuser = set_password_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
                       
        if request.POST['form'] == "add_info":
            add_info_form = EditAdditionalInfoForm(request.POST or None, 
                    instance=rhizomeuser and RhizomeUser.objects.get(id=rhizomeuser.id))
            if add_info_form.is_valid():
                rhizomeuser = add_info_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
        
        if request.POST['form'] == "manage_email_form":   
            manage_email_form = ManageForm(request.POST)     
            if manage_email_form.is_valid():
                mailinglists = manage_email_form.cleaned_data['mailinglists']
                notice = manage_email_form.save(request, mailinglists)
                updated = "pass"
            else:
                updated = "fail"
        if updated == 'pass':
            moderator.process(rhizomeuser, request)
            return HttpResponseRedirect('/profiles/edit?updated=True')
    
    breadcrumb = (("Profiles", rhizomeuser.get_absolute_url()), ("Edit",None)) 
 
    if rhizomeuser.id == request.user.id:
        return render_to_response(
            "accounts/edit.html",
            {
            "rhizomeuser":rhizomeuser,
            "personal_info_form":personal_info_form,
            "account_info_form":account_info_form,
            "bio_form":bio_form,
            "add_info_form":add_info_form,
            "set_password_form":set_password_form,
            "manage_email_form":manage_email_form,
            "address_form":address_form,
            "updated": updated,
            "breadcrumb":breadcrumb,
            "today": datetime.datetime.now(),
            }, 
            context
            )
    else:
        return HttpResponseRedirect(reverse(profiles_list))

Example 55

Project: CityCircles
Source File: views.py
View license
def test2(request, from_zl=DEFAULT_ZOOM, to_zl=DEFAULT_ZOOM, center_x=WIDTH/2, center_y=HEIGHT/2, from_origin_x=DEFAULT_VIEWALBE_ORIGIN_LL_X, from_origin_y = DEFAULT_VIEWALBE_ORIGIN_LL_Y):
    dct_return = {
        "points": "", #json encoded list of points to draw
        "tiles": "", #json encoded list of tiles
        "world_origin_x": from_origin_x,  #default to the from origin
        "world_origin_y": from_origin_y,
        "curr_zl": to_zl,
        "nxt_zl": False
    }
    
    ZOOM_RATIOS = {
    10: [1,1],
    12: [255.92568888889946/1023.70276,
         256.0/1024.0],
    15: [255.92568888889946/8189.62204,
         256.0/8192.0]
    }
    
    ZOOM_SCREEN_SIZES = {
        10: [WIDTH, HEIGHT],
        12: [WIDTH / ZOOM_RATIOS[12][0], HEIGHT / ZOOM_RATIOS[12][1]],
        15: [WIDTH / ZOOM_RATIOS[15][0], HEIGHT / ZOOM_RATIOS[15][1]],
    }
    
    ZOOM_WORLD_ORIGINS = {
        10: [49358.074311111101,
             157103.0],
        12: [197432.2972444444,
             627389.53504310793],
        15: [1579458.3779555552,
             5019116.2803448634]
    }
    
    #import rpdb2; rpdb2.start_embedded_debugger("password")
    from_zl = int(from_zl)
    to_zl = int(to_zl)
    center_x = int(center_x)
    center_y = HEIGHT - int(center_y)
    from_origin_x = int(from_origin_x)
    from_origin_y = int(from_origin_y)
    
    if ZOOMS.index(to_zl) == (len(ZOOMS) - 1):
        dct_return["nxt_zl"] = to_zl
    else:
        dct_return["nxt_zl"] = ZOOMS[ZOOMS.index(to_zl) + 1]    
    
    import rpdb2; rpdb2.start_embedded_debugger("password")
    #CONVERT CENTER_X, CENTER_Y TO METERS AT FROM ZOOM LEVEL
    from_zl = int(from_zl)
    #ll_m_x, ll_m_y = mercator.LatLonToMeters(MAP_LL_LAT, MAP_LL_LONG)
    #this is the x,y values for the world map origin at the from zoom level
    #ll_x, ll_y = mercator.MetersToPixels(ll_m_x, ll_m_y, from_zl)
    ll_x = from_origin_x
    ll_y = from_origin_y
    
    #center_x, center_y origin at the from zoom level
    c_w_x = ll_x + center_x
    c_w_y = ll_y + center_y
    
    #now make this meters
    c_w_m_x, c_w_m_y = mercator.PixelsToMeters(c_w_x, c_w_y, from_zl)
    
    #NOW MAKE THIS CENTER_X, CENTER_Y AT THE NEW ZOOM LEVEL
    existing_n_c_w_x, existing_n_c_w_y = mercator.MetersToPixels(c_w_m_x, c_w_m_y, to_zl)
    
    n_c_x = ZOOM_SCREEN_SIZES[to_zl][0] * (center_x / ZOOM_SCREEN_SIZES[from_zl][0])
    n_c_y = ZOOM_SCREEN_SIZES[to_zl][1] * (center_y / ZOOM_SCREEN_SIZES[from_zl][1])
    
    n_c_w_x = ZOOM_WORLD_ORIGINS[to_zl][0] + n_c_x
    n_c_w_y = ZOOM_WORLD_ORIGINS[to_zl][1] + n_c_y
    
    #CALCULATE THE NEW ZOOM LVLS ORIGIN IN THE WORLD
    n_ll_w_x = round(n_c_w_x - (WIDTH / 2)) #new lower left world x
    n_ll_w_y = round(n_c_w_y - (HEIGHT / 2)) # " y
    
    dct_return["world_origin_x"] = n_ll_w_x
    dct_return["world_origin_y"] = n_ll_w_y
    
    n_ur_w_x = n_ll_w_x + WIDTH
    n_ur_w_y = n_ll_w_y + HEIGHT
    
    li_tiles = []
    
    pnt_ll_w = pntsandrects.Point(n_ll_w_x, n_ll_w_y)
    pnt_ur_w = pntsandrects.Point(n_ur_w_x, n_ur_w_y)
    viewable_rect = pntsandrects.Rect(pnt_ll_w, pnt_ur_w)
    
    #MAKE A LIST OF TILES AT THIS ZOOM LEVEL THAT TOUCH THE VIEWABLE AREA
    for model_tile in Tile.objects.filter(level=to_zl):
        import rpdb2; rpdb2.start_embedded_debugger("password")
        #CONVERT THE TILES X,Y VALUES TO WORLD PIXEL X,Y AT THIS NEW ZOOM LEVEL
        #THE MAP TILES X,Y VALUES ARE IN RELATION TO THE MAX BOUNDS OF THE MAP, NOT VIEWABLE AREA
        #import rpdb2; rpdb2.start_embedded_debugger("password")
        #ll_m_x, ll_m_y = mercator.LatLonToMeters(MAP_LL_LAT, MAP_LL_LONG)
        #atile_origin_x, atile_origin_y = mercator.MetersToPixels(ll_m_x, ll_m_y, to_zl)
        
        tile_origin_x, tile_origin_y = ZOOM_WORLD_ORIGINS[to_zl]
        
        n_tile_ll_w_x = round(tile_origin_x + model_tile.ll_x)
        n_tile_ll_w_y = round(tile_origin_y + model_tile.ll_y)
        
        tile_pnt_ll_w = pntsandrects.Point(n_tile_ll_w_x, n_tile_ll_w_y)
        tile_pnt_ur_w = pntsandrects.Point(n_tile_ll_w_x + model_tile.size_x, n_tile_ll_w_y + model_tile.size_y)
        tile_rect = pntsandrects.Rect(tile_pnt_ll_w, tile_pnt_ur_w)
        if viewable_rect.overlaps(tile_rect):
            li_tiles.append(["/" + model_tile.fl_name, n_tile_ll_w_x - n_ll_w_x, HEIGHT - (TILE_SIZE + (n_tile_ll_w_y - n_ll_w_y)) ])
            
    #NOW THE LIGHTRAIL LINES
    li_shapes = []
            
    dct_return["tiles"] = simplejson.dumps(li_tiles)
    dct_return["points"] = simplejson.dumps(li_shapes)
    return render_to_response('test.html', dct_return)

Example 56

Project: splunk-webframework
Source File: views.py
View license
@staff_member_required
def model_detail(request, app_label, model_name):
    if not utils.docutils_is_available:
        return missing_docutils_page(request)

    # Get the model class.
    try:
        app_mod = models.get_app(app_label)
    except ImproperlyConfigured:
        raise Http404(_("App %r not found") % app_label)
    model = None
    for m in models.get_models(app_mod):
        if m._meta.object_name.lower() == model_name:
            model = m
            break
    if model is None:
        raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % {'model_name': model_name, 'app_label': app_label})

    opts = model._meta

    # Gather fields/field descriptions.
    fields = []
    for field in opts.fields:
        # ForeignKey is a special case since the field will actually be a
        # descriptor that returns the other object
        if isinstance(field, models.ForeignKey):
            data_type = field.rel.to.__name__
            app_label = field.rel.to._meta.app_label
            verbose = utils.parse_rst((_("the related `%(app_label)s.%(data_type)s` object")  % {'app_label': app_label, 'data_type': data_type}), 'model', _('model:') + data_type)
        else:
            data_type = get_readable_field_data_type(field)
            verbose = field.verbose_name
        fields.append({
            'name': field.name,
            'data_type': data_type,
            'verbose': verbose,
            'help_text': field.help_text,
        })

    # Gather many-to-many fields.
    for field in opts.many_to_many:
        data_type = field.rel.to.__name__
        app_label = field.rel.to._meta.app_label
        verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': app_label, 'object_name': data_type}
        fields.append({
            'name': "%s.all" % field.name,
            "data_type": 'List',
            'verbose': utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name),
        })
        fields.append({
            'name'      : "%s.count" % field.name,
            'data_type' : 'Integer',
            'verbose'   : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name),
        })

    # Gather model methods.
    for func_name, func in model.__dict__.items():
        if (inspect.isfunction(func) and len(inspect.getargspec(func)[0]) == 1):
            try:
                for exclude in MODEL_METHODS_EXCLUDE:
                    if func_name.startswith(exclude):
                        raise StopIteration
            except StopIteration:
                continue
            verbose = func.__doc__
            if verbose:
                verbose = utils.parse_rst(utils.trim_docstring(verbose), 'model', _('model:') + opts.module_name)
            fields.append({
                'name': func_name,
                'data_type': get_return_data_type(func_name),
                'verbose': verbose,
            })

    # Gather related objects
    for rel in opts.get_all_related_objects() + opts.get_all_related_many_to_many_objects():
        verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': rel.opts.app_label, 'object_name': rel.opts.object_name}
        accessor = rel.get_accessor_name()
        fields.append({
            'name'      : "%s.all" % accessor,
            'data_type' : 'List',
            'verbose'   : utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name),
        })
        fields.append({
            'name'      : "%s.count" % accessor,
            'data_type' : 'Integer',
            'verbose'   : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name),
        })
    return render_to_response('admin_doc/model_detail.html', {
        'root_path': urlresolvers.reverse('admin:index'),
        'name': '%s.%s' % (opts.app_label, opts.object_name),
        'summary': _("Fields on %s objects") % opts.object_name,
        'description': model.__doc__,
        'fields': fields,
    }, context_instance=RequestContext(request))

Example 57

Project: cdr-stats
Source File: views.py
View license
@permission_required('user_profile.by_country', login_url='/')
@check_user_detail('accountcode')
@login_required
def cdr_country_report(request):
    """CDR country report

    **Attributes**:

        * ``template`` - cdr/country_report.html
        * ``form`` - CountryReportForm

    **Logic Description**:

        Retrieve call records from Postgresql for all countries
        and create reporting information for those countries
    """
    metric = 'nbcalls'
    tday = datetime.today()

    switch_id = 0
    hourly_charttype = "lineWithFocusChart"
    hourly_chartdata = {'x': []}
    country_id_list = []
    total_metric = 0

    # assign initial value in form fields
    form = CountryReportForm(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')
        country_id = form.cleaned_data['country_id']
        # convert list value in int
        country_id_list = [int(row) for row in country_id]
        # handle 0 (All) selection
        if 0 in country_id_list:
            country_id_list = []

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

    hourly_data = get_report_cdr_per_country(request.user, 'hour', start_date, end_date, switch_id, country_id_list)

    extra_serie = {
        "tooltip": {"y_start": "", "y_end": " " + metric},
        "date_format": "%d %b %y %H:%M%p"
    }
    for country in hourly_data[metric]["columns"]:
        hourly_chartdata['x'] = hourly_data[metric]["x_timestamp"]
        country_name = get_country_name(int(country)).encode('utf-8')
        hourly_chartdata['name' + str(country)] = country_name.decode('ascii', 'ignore').replace("'", " ")
        hourly_chartdata['y' + str(country)] = hourly_data[metric]["values"][str(country)]
        hourly_chartdata['extra' + str(country)] = 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"]

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

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

    # Build pie chart data for last 24h calls per country
    (xdata, ydata) = ([], [])
    for country in country_data:
        xdata.append(get_country_name(country["country_id"]))
        ydata.append(percentage(country["nbcalls"], total_calls))

    color_list = ['#FFC36C', '#FFFF9D', '#BEEB9F', '#79BD8F', '#FFB391',
        '#58A6A6', '#86BF30', '#F2D022', '#D9AA1E', '#D98236']

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

    country_extra = {
        'x_is_date': False,
        'x_axis_format': '',
        'tag_script_js': True,
        'jquery_on_ready': True,
    }

    data = {
        'action': 'tabs-1',
        'total_metric': total_metric,
        'start_date': start_date,
        'end_date': end_date,
        'metric': metric,
        'form': form,
        'NUM_COUNTRY': settings.NUM_COUNTRY,
        'hourly_charttype': hourly_charttype,
        'hourly_chartdata': hourly_chartdata,
        'hourly_chartcontainer': 'hourly_container',
        'hourly_extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %Y',
            'tag_script_js': True,
            'jquery_on_ready': False,
        },
        '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,

        'country_analytic_charttype': country_analytic_charttype,
        'country_analytic_chartdata': country_analytic_chartdata,
        'country_chartcontainer': 'country_piechart_container',
        'country_extra': country_extra,
        'top_country': top_country,
    }
    return render_to_response('cdr/country_report.html', data, context_instance=RequestContext(request))

Example 58

Project: cdr-stats
Source File: views.py
View license
@permission_required('user_profile.dashboard', login_url='/')
@check_user_detail('accountcode,voipplan')
@login_required
def cdr_dashboard(request):
    """CDR dashboard on the last 24 hours

    **Attributes**:

        * ``template`` - cdr/dashboard.html
        * ``form`` - SwitchForm

    **Logic Description**:

        Display calls aggregated information for the last 24hours, several report will be
        created and displayed such as hourly call report and hangup cause/country analytics.
    """
    logging.debug('CDR dashboard view start')
    form = SwitchForm(request.POST or None)

    if form.is_valid():
        logging.debug('CDR dashboard view with search option')
        switch_id = int(getvar(request, 'switch_id'))
    else:
        switch_id = 0

    # Get list of calls/duration for each of the last 24 hours
    (calls_hour_aggr, total_calls, total_duration, total_billsec, total_buy_cost, total_sell_cost) = custom_sql_matv_voip_cdr_aggr_last24hours(request.user, switch_id)

    # Build chart data for last 24h calls
    (xdata, ydata, ydata2, ydata3, ydata4, ydata5) = ([], [], [], [], [], [])
    for i in calls_hour_aggr:
        start_time = (time.mktime(calls_hour_aggr[i]['calltime'].timetuple()) * 1000)
        xdata.append(start_time)
        ydata.append(int(calls_hour_aggr[i]['nbcalls']))
        ydata2.append(int(calls_hour_aggr[i]['duration']/60))
        ydata3.append(int(calls_hour_aggr[i]['billsec']/60))
        ydata4.append(int(calls_hour_aggr[i]['buy_cost']))
        ydata5.append(int(calls_hour_aggr[i]['sell_cost']))

    tooltip_date = "%d %b %y %H:%M %p"
    extra_serie1 = {"tooltip": {"y_start": "", "y_end": " calls"}, "date_format": tooltip_date}
    extra_serie2 = {"tooltip": {"y_start": "", "y_end": " min"}, "date_format": tooltip_date}
    extra_serie3 = {"tooltip": {"y_start": "", "y_end": " min"}, "date_format": tooltip_date}
    extra_serie4 = {"tooltip": {"y_start": "", "y_end": ""}, "date_format": tooltip_date}
    extra_serie5 = {"tooltip": {"y_start": "", "y_end": ""}, "date_format": tooltip_date}

    kwargs1 = {}
    kwargs1['bar'] = True

    final_chartdata = {
        'x': xdata,
        'name1': 'Calls', 'y1': ydata, 'extra1': extra_serie1, 'kwargs1': kwargs1,
        'name2': 'Duration', 'y2': ydata2, 'extra2': extra_serie2,
        'name3': 'Billsec', 'y3': ydata3, 'extra3': extra_serie3,
        'name4': 'Buy cost', 'y4': ydata4, 'extra4': extra_serie4,
        'name5': 'Sell cost', 'y5': ydata5, 'extra5': extra_serie5,
    }
    final_charttype = "linePlusBarChart"

    # Get top 5 of country calls for last 24 hours
    country_data = custom_sql_aggr_top_country_last24hours(request.user, switch_id, limit=5)

    # Build pie chart data for last 24h calls per country
    (xdata, ydata) = ([], [])
    for country in country_data:
        xdata.append(get_country_name(country["country_id"]))
        ydata.append(percentage(country["nbcalls"], total_calls))

    color_list = ['#FFC36C', '#FFFF9D', '#BEEB9F', '#79BD8F', '#FFB391']
    extra_serie = {"tooltip": {"y_start": "", "y_end": " %"}, "color_list": color_list}
    country_analytic_chartdata = {'x': xdata, 'y1': ydata, 'extra1': extra_serie}
    country_analytic_charttype = "pieChart"

    country_extra = {
        'x_is_date': False,
        'x_axis_format': '',
        'tag_script_js': True,
        'jquery_on_ready': True,
    }

    # Get top 10 of hangup cause calls for last 24 hours
    hangup_cause_data = custom_sql_aggr_top_hangup_last24hours(request.user, switch_id)

    # hangup analytic pie chart data
    (xdata, ydata) = ([], [])
    for hangup_cause in hangup_cause_data:
        xdata.append(str(get_hangupcause_name(hangup_cause["hangup_cause_id"])))
        ydata.append(str(percentage(hangup_cause["nbcalls"], total_calls)))

    color_list = ['#2A343F', '#7E8282', '#EA9664', '#30998F', '#449935']
    extra_serie = {"tooltip": {"y_start": "", "y_end": " %"}, "color_list": color_list}
    hangup_analytic_chartdata = {'x': xdata, 'y1': ydata, 'extra1': extra_serie}
    hangup_analytic_charttype = "pieChart"

    hangup_extra = country_extra

    logging.debug("Result calls_hour_aggr %d" % len(calls_hour_aggr))
    logging.debug("Result hangup_cause_data %d" % len(hangup_cause_data))
    logging.debug("Result country_data %d" % len(country_data))

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

    final_extra = {
        'x_is_date': True,
        'x_axis_format': '%H:%M',
        # 'x_axis_format': '%d %b %Y',
        'tag_script_js': True,
        'jquery_on_ready': True,
        'focus_enable': True,
    }

    logging.debug('CDR dashboard view end')
    variables = {
        'total_calls': total_calls,
        'total_duration': int_convert_to_minute(total_duration),
        'total_buy_cost': total_buy_cost,
        'total_sell_cost': total_sell_cost,
        'metric_aggr': metric_aggr,
        'country_data': country_data,
        'hangup_analytic': hangup_cause_data,
        'form': form,
        'final_chartdata': final_chartdata,
        'final_charttype': final_charttype,
        'final_chartcontainer': 'final_container',
        'final_extra': final_extra,
        'hangup_analytic_charttype': hangup_analytic_charttype,
        'hangup_analytic_chartdata': hangup_analytic_chartdata,
        'hangup_chartcontainer': 'hangup_piechart_container',
        'hangup_extra': hangup_extra,
        'country_analytic_charttype': country_analytic_charttype,
        'country_analytic_chartdata': country_analytic_chartdata,
        'country_chartcontainer': 'country_piechart_container',
        'country_extra': country_extra,
    }
    return render_to_response('cdr/dashboard.html', variables, context_instance=RequestContext(request))

Example 59

Project: Subterfuge
Source File: views.py
View license
def conf(request, module):
      # Read in subterfuge.conf
   with open(str(os.path.dirname(__file__)).rstrip("abcdefghijklmnnnopqrstruvwxyz") + 'subterfuge.conf', 'r') as file:
      conf = file.readlines()

      # Subterfuge Settings Configuration
      # Edit subterfuge.conf
   if module == "settings":
         #Attack Setup
      try:
         setup.objects.update(iface = request.POST["iface"])
         conf[15] = request.POST["iface"] + "\n"
         print "Using Interface => " + request.POST["iface"]
      except:
         pass
      
      try:
         if request.POST["auto"] == "true":
            setup.objects.update(autoconf = "yes")
            conf[20] = "yes" + "\n"
            print "Auto Configure  => yes"
         else:
            setup.objects.update(autoconf = "no")
            conf[20] = "no" + "\n"
            print "Auto Configure  => no"
      except:
         pass
         
      try:
         setup.objects.update(gateway = request.POST["agw"])
         conf[17] = request.POST["agw"] + "\n"
         print "Using Gateway   => " + request.POST["agw"]
      except:
         pass

      try:
         setup.objects.update(proxymode = request.POST["proxymode"])
         print "Using Gateway   => " + request.POST["proxymode"]
      except:
         pass
         
      try:
         setup.objects.update(gateway = request.POST["mgw"])
         conf[17] = request.POST["mgw"] + "\n"
         print "Using Gateway   => " + request.POST["mgw"]
      except:
         pass

         #Get the Local IP Address
      try:
         f = os.popen("ifconfig " + request.POST["iface"] + " | grep \"inet addr\" | sed -e \'s/.*addr://;s/ .*//\'")
         temp2 = ''
         temp3 = ''
         temp = f.readline().rstrip('\n')
   
         ipaddress = re.findall(r'\d*.\d*.\d*.\d*', temp)[0]
         conf[26] = ipaddress + "\n"
         setup.objects.update(ip = ipaddress)
      except:
         pass
         
         
         #Configuration
      try:
         setup.objects.update(ploadrate = request.POST["ploadrate"])
         setup.objects.update(injectrate = request.POST["injectrate"])
         if request.POST["smartarp"] == "true":
            setup.objects.update(smartarp = "yes")
         elif request.POST["smartarp"] == "false":
            setup.objects.update(smartarp = "no")
         setup.objects.update(arprate = request.POST["arprate"])
      except:
         pass
      
      
         #Vectors
      try:
         if request.POST["active"] == "true":
            vectors.objects.filter(name = request.POST["vector"]).update(active = "yes")
         else:
            vectors.objects.filter(name = request.POST["vector"]).update(active = "no")
            
            #Wireless AP Generator Settings 
         if request.POST["vector"] == "ARP Cache Poisoning":
            arppoison.objects.update(target = request.POST["target"])
            arppoison.objects.update(method = request.POST["arpmethod"])
         
            #Wireless AP Generator Settings
         if request.POST["vector"] == "Wireless AP Generator":
            apgen.objects.update(essid = request.POST["essid"])
            apgen.objects.update(channel = request.POST["channel"])
            apgen.objects.update(atknic = request.POST["atknic"])
            apgen.objects.update(netnic = request.POST["netnic"])
      except:
         pass
         
         
         #Advanced
      try:
         scanip = request.POST["scantargetip"]
         print "Importing Nmap scan for: " + scanip
         
            #Get/Write Files
         if request.FILES['scanresults']:
            scanresults = request.FILES['scanresults']
            dest = open(str(os.path.dirname(__file__)).rstrip("abcdefghijklmnnnopqrstruvwxyz") + 'utilities/scans/' + scanip + '.xml', 'wb+')
            for chunk in scanresults.chunks():
               dest.write(chunk)
            dest.close()
               #Execute Scan
            os.system('python ' + str(os.path.dirname(__file__)).rstrip("abcdefghijklmnnnopqrstruvwxyz") + 'utilities/scan.py ' + scanip)
            
               #Relay Template Variables
         return render_to_response("settings.ext", {
            "config"    :   config,
            "conf"      :   str(config[20]).rstrip('\n'),
            "iface"	   :   result,
            "gateway"   :   gw,
            "status"    :   status,
            "setup"     :   currentsetup,
         })    
      except:
         pass
         

   if module == "update":
      os.system('apt-get install subterfuge')

   if module == "exportcreds":
      os.system('python ' + str(os.path.dirname(__file__)).rstrip("abcdefghijklmnnnopqrstruvwxyz") + 'exportcreds.py')

      #################################
      #Subterfuge Module Configurations
      #################################
      
   if module == "httpinjection":   
      httpcodeinjection(request, conf)
      
   elif module == "tunnelblock":   
      tunnelblock()
      
   else:
      for mod in installed.objects.all():
         if module == mod.name:
           os.system('python ' + str(os.path.dirname(__file__)).rstrip("abcdefghijklmnnnopqrstruvwxyz") + 'modules/' + module + '/' + module + '.py &')
   
              
      #################################
      #  END MODULE CONFIGURATION
      #################################
   
      # Write to subterfuge.conf
   with open(str(os.path.dirname(__file__)).rstrip("abcdefghijklmnnnopqrstruvwxyz") + 'subterfuge.conf', 'w') as file:
      file.writelines(conf)
      
      
      # Call Index Page
      # Check Arpspoof status
   command = "ps -A 1 | sed -e '/arpmitm/!d;/sed -e/d;s/^ //;s/ pts.*//'"
   a = os.popen(command)
   reply = a.read()
   if(len(reply)>1):
	   status = "on"
   else:
	   status = "off"
   
   if module == "httpinjection" or module == "tunnelblock":
            #Relay Template Variables
        modules = installed.objects.all()
        return render_to_response("plugins.ext", {
            "modules"   :   modules,
        })
   else:
         #Relay Template Variables
      return render_to_response(request.META['HTTP_REFERER'].split('/')[3] + ".ext", {
         "status"    :   status,
      })

Example 60

Project: django-nonrel
Source File: views.py
View license
def model_detail(request, app_label, model_name):
    if not utils.docutils_is_available:
        return missing_docutils_page(request)

    # Get the model class.
    try:
        app_mod = models.get_app(app_label)
    except ImproperlyConfigured:
        raise Http404(_("App %r not found") % app_label)
    model = None
    for m in models.get_models(app_mod):
        if m._meta.object_name.lower() == model_name:
            model = m
            break
    if model is None:
        raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % {'model_name': model_name, 'app_label': app_label})

    opts = model._meta

    # Gather fields/field descriptions.
    fields = []
    for field in opts.fields:
        # ForeignKey is a special case since the field will actually be a
        # descriptor that returns the other object
        if isinstance(field, models.ForeignKey):
            data_type = related_object_name = field.rel.to.__name__
            app_label = field.rel.to._meta.app_label
            verbose = utils.parse_rst((_("the related `%(app_label)s.%(data_type)s` object")  % {'app_label': app_label, 'data_type': data_type}), 'model', _('model:') + data_type)
        else:
            data_type = get_readable_field_data_type(field)
            verbose = field.verbose_name
        fields.append({
            'name': field.name,
            'data_type': data_type,
            'verbose': verbose,
            'help_text': field.help_text,
        })

    # Gather many-to-many fields.
    for field in opts.many_to_many:
        data_type = related_object_name = field.rel.to.__name__
        app_label = field.rel.to._meta.app_label
        verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': app_label, 'object_name': data_type}
        fields.append({
            'name': "%s.all" % field.name,
            "data_type": 'List',
            'verbose': utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name),
        })
        fields.append({
            'name'      : "%s.count" % field.name,
            'data_type' : 'Integer',
            'verbose'   : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name),
        })

    # Gather model methods.
    for func_name, func in model.__dict__.items():
        if (inspect.isfunction(func) and len(inspect.getargspec(func)[0]) == 1):
            try:
                for exclude in MODEL_METHODS_EXCLUDE:
                    if func_name.startswith(exclude):
                        raise StopIteration
            except StopIteration:
                continue
            verbose = func.__doc__
            if verbose:
                verbose = utils.parse_rst(utils.trim_docstring(verbose), 'model', _('model:') + opts.module_name)
            fields.append({
                'name': func_name,
                'data_type': get_return_data_type(func_name),
                'verbose': verbose,
            })

    # Gather related objects
    for rel in opts.get_all_related_objects() + opts.get_all_related_many_to_many_objects():
        verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': rel.opts.app_label, 'object_name': rel.opts.object_name}
        accessor = rel.get_accessor_name()
        fields.append({
            'name'      : "%s.all" % accessor,
            'data_type' : 'List',
            'verbose'   : utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name),
        })
        fields.append({
            'name'      : "%s.count" % accessor,
            'data_type' : 'Integer',
            'verbose'   : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name),
        })
    return render_to_response('admin_doc/model_detail.html', {
        'root_path': get_root_path(),
        'name': '%s.%s' % (opts.app_label, opts.object_name),
        'summary': _("Fields on %s objects") % opts.object_name,
        'description': model.__doc__,
        'fields': fields,
    }, context_instance=RequestContext(request))

Example 61

Project: classic.rhizome.org
Source File: admin.py
View license
    def url_inventory(self, request):
        '''
        creates a csv file compiling the http status of artbase artworks and their urls and locations
        
        '''
        context_instance = RequestContext(request)
        opts = self.model._meta
        admin_site = self.admin_site
        completed_message = None

        writer = csv.writer(open(os.path.join(settings.MEDIA_ROOT, "artbase/data/artbase_broken_urls_inventory_%s.csv" \
            % datetime.date.today(), "wb")))
                
        writer.writerow(['ARTWORK ID', 'ARTWORK TITLE', 'ARTWORK URL', 'URL STATUS', 'LOCATION', 'LOCATION STATUS','UPDATE NOTICE']) 
        all_works = ArtworkStub.objects.filter(status="approved")

        handler = urllib2.UnknownHandler()
        opener = urllib2.build_opener(handler)
        urllib2.install_opener(opener)    
        
        # timeout in seconds
        timeout = 15
        socket.setdefaulttimeout(timeout)
        
        if request.method == "POST":
            if request.POST.get("run_inventory"):
                for work in all_works:   
                    url_response = None
                    url_error_msg = None
                    url_status = None
                    location_response = None
                    location_status = None
                    location_error_msg = None
                    updating_notice = None
            
                    #a few hacks to make sure the url is formatted correctly
                    if "/artbase/" in work.url:
                        if "http://archive.rhizome.org" not in work.url:
                            if "http://" not in work.url:
                                work.url = "http://archive.rhizome.org%s" % work.url
                                updating_notice = "Make sure has full rhizome archives url (http://archive.rhizome.org/....)"
        
                    if "/artbase/" in work.location:
                        if "http://archive.rhizome.org" not in work.location:
                            if "http://" not in work.location:
                                work.location = "http://archive.rhizome.org%s" % work.location
                                updating_notice = "Make sure has full rhizome archives url (http://archive.rhizome.org/....)"
                    if "http://" not in work.url:
                        work.url = "http://%s" % work.url
                        updating_notice = "Make sure has url including 'http://'"
        
                    if "http://" not in work.location:
                        work.location = "http://%s" % work.location
                        updating_notice = "Make sure has url including 'http://'"
                             
                    try:
                        url_response = urllib2.urlopen(work.url, timeout = 15)
                    except (urllib2.URLError, httplib.BadStatusLine, httplib.InvalidURL, httplib.HTTPException,httplib.UnknownProtocol), e:
                        if hasattr(e, 'reason'):
                                if isinstance(e.reason, socket.timeout):
                                    url_error_msg = 'Failed to reach server. TIMED OUT '
                                else:
                                    url_error_msg = 'Failed to reach server. Reason: %s ' % e.reason
                        elif hasattr(e, 'code'):
                            url_error_msg = "The server couldn't fulfill the request. Error code: %s" % e.code
                        else:
                            url_error_msg = "Failed to reach server!"                    
                    except:
                        url_error_msg = "Failed to reach server!"
                          
                    if url_response:
                        url_status = "SUCCESS"
                    else:
                        url_status = url_error_msg
                    
                    
                    if work.location:
                        try:
                            location_response = urllib2.urlopen(work.location, timeout = 15)
                        except (urllib2.URLError, httplib.BadStatusLine, httplib.InvalidURL, \
                                httplib.HTTPException,httplib.UnknownProtocol), e:
                            if hasattr(e, 'reason'):
                                if isinstance(e.reason, socket.timeout):
                                    url_error_msg = 'Failed to reach server. TIMED OUT '
                                else:
                                    location_error_msg = 'Failed to reach a server. Reason: %s ' % e.reason
                            elif hasattr(e, 'code'):
                                location_error_msg = "The server couldn't fulfill the request. Error code: %s" % e.code
                            else:
                                location_error_msg = "Failed to reach server!"
                    
                    if location_response:
                        location_status = "SUCCESS"
                    else:
                        location_status = location_error_msg
                 
                    if location_error_msg or url_error_msg and not updating_notice:
                        updating_notice = "This work has broken links"                 
                    
                    if updating_notice:
                        writer.writerow([    
                            "%s" % work.id,
                            "%s" % work.title,
                            "%s" % work.url,
                            "%s" % url_status,
                            "%s" % work.location,
                            "%s" % location_status,
                            "%s" % updating_notice,
                        ])
                        
                report_email = EmailMessage('ArtBase Broken URLs Inventory Report', 'Report Attached.', settings.ARTBASE_GROUP_EMAIL,
                                            [settings.ARTBASE_GROUP_EMAIL], headers = {'Reply-To': settings.ARTBASE_GROUP_EMAIL})  
                    
                report_email.attach('artbase_broken_urls_inventory_%s.csv' % datetime.date.today(), writer, 'text/csv')
                report_email.send()
                
                completed_message = True
            
        d = {'admin_site': admin_site.name, 
             'title': "Inventory Broken Artwork URLS", 
             'opts': "Artworks", 
             'app_label': opts.app_label,
             "completed_message":completed_message
             }
             
        return render_to_response('admin/artbase/url_inventory.html', d, context_instance)                

Example 62

Project: Adlibre-DMS
Source File: views.py
View license
@login_required
@group_required(SEC_GROUP_NAMES['search'])
def search_type(request, step, template='mdtui/search.html'):
    """Search Step 1: Select Search MDT

    @param request: is a Django request object
    @param step: is a current step name (for template rendering)
    @param template: is a name of template for this view"""
    warnings = []
    cleanup_indexing_session(request)

    # Initialising MDT or Docrule form according to data provided
    valid_call = True
    required_mdt = True
    required_docrule = True
    if request.POST:
        # Cleaning search session selections
        cleanup_search_session(request)
        cleanup_mdts(request)
        # Checking if docrule or mdt selected
        try:
            if request.POST['docrule']:
                required_mdt = False
        except KeyError:
            pass
        try:
            if request.POST['mdt']:
                required_docrule = False
        except KeyError:
            pass
        # Do not process in case docrule and MDT provided
        try:
            if request.POST['docrule'] and request.POST['mdt']:
                valid_call = False
                warnings.append(MDTUI_ERROR_STRINGS['NO_MDT_NO_DOCRULE'])
        except KeyError:
            pass

    # Rendering forms accordingly
    mdts_filtered_form = make_mdt_select_form(request.user, required_mdt)
    mdts_form = mdts_filtered_form(request.POST or None)
    docrules_filtered_form = make_document_type_select_form(request.user, required_docrule)
    docrules_form = docrules_filtered_form(request.POST or None)

    # POST Validation for either docrule OR mdt selected
    if request.POST and valid_call:
        if mdts_form.is_valid() and not required_docrule:
            mdts = None
            mdt_form_id = None
            try:
                mdt_form_id = mdts_form.data["mdt"]
            except KeyError:
                pass
            # CouchDB connection Felt down warn user
            if mdt_form_id:
                try:
                    mdt_names = get_mdt_from_search_mdt_select_form(mdt_form_id, mdts_filtered_form)
                    request.session['search_mdt_id'] = mdt_form_id
                    mdts = get_mdts_by_names(mdt_names)
                    docrules_list = mdts['1']['docrule_id']
                    if not request.user.is_superuser:
                        request.session['search_docrule_ids'] = filter_permitted_docrules(docrules_list, request.user)
                    else:
                        request.session['search_docrule_ids'] = docrules_list
                except RequestError:
                    warnings.append(MDTUI_ERROR_STRINGS['NO_DB'])
                if mdts:
                    request.session['mdts'] = mdts
                    if valid_call:
                        return HttpResponseRedirect(reverse('mdtui-search-options'))
            else:
                if not MDTUI_ERROR_STRINGS['NO_MDTS'] in warnings:
                    warnings.append(MDTUI_ERROR_STRINGS['NO_MDTS'])

        if docrules_form.is_valid() and not required_mdt:
            # If Docrule selected than MDT is not required and MDT's form is valid in fact
            docrule_form_id = None
            try:
                docrule_form_id = docrules_form.data["docrule"]
            except KeyError:
                pass
            if docrule_form_id:
                request.session['searching_docrule_id'] = docrule_form_id
                mdts = get_mdts_for_docrule(docrule_form_id)
                if mdts:
                    request.session['mdts'] = mdts
                    if valid_call:
                        return HttpResponseRedirect(reverse('mdtui-search-options'))
            else:
                if not MDTUI_ERROR_STRINGS['NO_MDTS'] in warnings:
                    warnings.append(MDTUI_ERROR_STRINGS['NO_MDTS'])
    else:
        # Populating forms with preexisting data if provided
        mdt_id = None
        docrule_id = None
        # Trying to set docrule if previously selected
        try:
            docrule_id = request.session['searching_docrule_id']
        except KeyError:
            pass
        if docrule_id:
            docrules_form = docrules_filtered_form({'docrule': docrule_id})

        # Trying to set mdt if previously selected
        try:
            mdt_id = request.session['search_mdt_id']
        except KeyError:
            pass
        if mdt_id:
            mdts_form = mdts_filtered_form({'mdt': mdt_id})

    context = {
        'warnings': warnings,
        'step': step,
        'mdts_form': mdts_form,
        'docrules_form': docrules_form,
    }
    return render_to_response(template, context, context_instance=RequestContext(request))

Example 63

Project: tendenci
Source File: views.py
View license
def index(request, form_class=SubmitContactForm, template_name="form.html"):

    if request.method == "GET":
        # event-log view
        EventLog.objects.log(instance=Contact(), action='viewed')

    if request.method == "POST":
        event_log_dict = {}
        form = form_class(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')

            if listed_in_email_block(email):
                # listed in the email blocks - it's a spam email we want to block
                # log the spam
                EventLog.objects.log()

                # redirect normally so they don't suspect
                return HttpResponseRedirect(reverse('form.confirmation'))

            address = form.cleaned_data.get('address')
            city = form.cleaned_data.get('city')
            state = form.cleaned_data.get('state')
            zipcode = form.cleaned_data.get('zipcode')
            country = form.cleaned_data.get('country')
            phone = form.cleaned_data.get('phone')
            url = form.cleaned_data.get('url')
            message = form.cleaned_data.get('message')

            exists = User.objects.filter(
                first_name__iexact=first_name,
                last_name__iexact=last_name,
                email__iexact=email,
            ).exists()

            if request.user.is_anonymous():
                username = first_name.replace(' ', '')
                if last_name:
                    username = username + '_' + last_name.replace(' ', '')
                username = username.lower()
                try:
                    User.objects.get(username=username)
                    x = User.objects.filter(first_name=first_name).count()
                    username = username + '_' + unicode(x)
                except User.DoesNotExist:
                    pass

                contact_user = User(
                    username=username,
                    email=email,
                    first_name=first_name,
                    last_name=last_name,
                )

                contact_user.is_active = False
                contact_user.save()
                profile = Profile(user=contact_user, owner=contact_user, creator=User.objects.get(pk=1),
                                  address=address, country=country, city=city, state=state,
                                  url=url, phone=phone, zipcode=zipcode)
                profile.save()
                sf_id = create_salesforce_contact(profile)

                # if exists:
                #     event_log_dict['description'] = 'logged-out submission as existing user'
                # else:
                event_log_dict['description'] = 'logged-out submission as new user'

            else:  # logged in user
                self_submit = all([
                    request.user.first_name.lower().strip() == first_name.lower().strip(),
                    request.user.last_name.lower().strip() == last_name.lower().strip(),
                    request.user.email.lower().strip() == email.lower().strip(),
                ])

                contact_user = request.user

                if exists:
                    if self_submit:
                        event_log_dict['description'] = 'logged-in submission as self'
                    else:
                        event_log_dict['description'] = 'logged-in submission as existing user'
                else:
                    event_log_dict['description'] = 'logged-in submission as non-existing user'

            contact_kwargs = {
                'first_name': first_name,
                'last_name': last_name,
                'message': message,
                'user': contact_user,
            }

            contact = Contact(**contact_kwargs)
            contact.allow_anonymous_view = False
            contact.save()

            if address or city or state or zipcode or country:
                address_kwargs = {
                    'address': address,
                    'city': city,
                    'state': state,
                    'zipcode': zipcode,
                    'country': country,
                }
                obj_address = Address(**address_kwargs)
                obj_address.save()  # saves object
                contact.addresses.add(obj_address)  # saves relationship

            if phone:
                obj_phone = Phone(number=phone)
                obj_phone.save()  # saves object
                contact.phones.add(obj_phone)  # saves relationship

            if email:
                obj_email = Email(email=email)
                obj_email.save()  # saves object
                contact.emails.add(obj_email)  # saves relationship

            if url:
                obj_url = URL(url=url)
                obj_url.save()  # saves object
                contact.urls.add(obj_url)  # saves relationship

            site_name = get_setting('site', 'global', 'sitedisplayname')
            message_link = get_setting('site', 'global', 'siteurl')

            # send notification to administrators
            # get admin notice recipients
            recipients = get_notice_recipients('module', 'contacts', 'contactrecipients')
            if recipients:
                if notification:
                    extra_context = {
                    'reply_to': email,
                    'contact': contact,
                    'first_name': first_name,
                    'last_name': last_name,
                    'address': address,
                    'city': city,
                    'state': state,
                    'zipcode': zipcode,
                    'country': country,
                    'phone': phone,
                    'email': email,
                    'url': url,
                    'message': message,
                    'message_link': message_link,
                    'site_name': site_name,
                    }
                    notification.send_emails(recipients, 'contact_submitted', extra_context)

            # event-log (logged in)
            event_log = EventLog.objects.log(
                instance=contact,
                user=contact_user,
                action='submitted',
                **event_log_dict
            )

            event_log.url = contact.get_absolute_url()
            event_log.save()

            return HttpResponseRedirect(reverse('form.confirmation'))
        else:
            return render_to_response(template_name, {'form': form},
                context_instance=RequestContext(request))

    form = form_class()
    return render_to_response(template_name, {'form': form},
        context_instance=RequestContext(request))

Example 64

Project: Adlibre-TMS
Source File: views.py
View license
@login_required
def timesheets(request, data_id = None, template_name='tms/timesheets.html',
               form_template_name='tms/timesheets_form.html',
               entry_template_name='tms/timesheets_single_entry.html',
               post_save_redirect='tms_timesheets'):
    """Displaying/Adding/Editing existing Timesheet entry in database.

    Used with AJAX calls now. Main gear view for Timesheets.
    
    - GET to this view retrieves Whole timesheets page (form and entries paginated table)
    - POST to this view: 
        - Adds a new entry 
            (When request.POST['data_id'] is not given (equal to u('') or u(' ') ))
        - Edits an entry 
            (Upon request.POST['data_id'] is equal to some Timesheet PK)
            (Creates a form instance with model of provided PK and validates it)
    - returns single Timesheet entry when form is valid
    - returns single Timesheet entry when form is valid and item was edited
        (Response contains <div class="edited_item_returned"></div> in this case... 
        To check for editing/adding entry in AJAX side)
    - Returns form with errors in case some errors occurred in form validation
    
    """
    # storing sessin user position
    request.session['enter_url'] = reverse('tms_timesheets')
    #checking for the edit data_id exists in the call and selecting behavior
    if request.method == 'POST' and data_id != ('' or ' '):
        try:
            data_id = request.POST['data_id']
            timesheet = get_object_or_404(Timesheet, pk=data_id)
            form = TimesheetForm(request.POST or None, instance=timesheet)
            edit_ajax = True
        except:
            data_id = ' '
            edit_ajax = False
            form = TimesheetForm(request.POST or None)
    else:
        form = TimesheetForm(request.POST or None)
    # form validation
    if request.method == 'POST' and form.is_valid():
        if request.POST.get('save', None):
            # saving data with form
            obj = form.save(commit=False)
            employee, created = Employee.objects.get_or_create(user=request.user)
            obj.employee = employee
            obj.save()
            # Add message to admin
            messages.add_message(request, messages.INFO, 'Timesheet entry was added successfully')
            context = {
                       'object': obj,
                       'edit_ajax': edit_ajax,
                       'add_init': True
                       }
            return render_to_response(entry_template_name, context, context_instance=RequestContext(request))
    elif request.method == 'POST' and not form.is_valid():
        #returning form with errors
        context = {
                   'form': form,
                   'edit_pk': data_id,
                   }
        return render_to_response(form_template_name, context, context_instance=RequestContext(request))

    timesheets_list = Timesheet.objects.filter(employee__user=request.user,
                                        is_submitted=False,
                                        is_billed=False).order_by('-start_time')
    # adding context vars for proper form init (described in project Wiki/TimesheetEntry)
    latest_date = ''
    latest_job = ''
    timesheets_today = timesheets_list.filter(start_time__startswith=str(datetime.date.today())).order_by('-end_time')
    if timesheets_today:
        latest_date = timesheets_today[0].end_time
        latest_job = timesheets_today[0].job.pk
    #returning empty form
    context = {
        'form': form,
        'object_list': timesheets_list,
        'init_latest_date':  latest_date,
        'init_latest_job' : latest_job,
        }
    return render_to_response(template_name, context, context_instance=RequestContext(request))

Example 65

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

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

	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()

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

	def get_all_vm():
		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_all_stg():
		try:
			storages = []
			for name in conn.listStoragePools():
				storages.append(name)
			for name in conn.listDefinedStoragePools():
				storages.append(name)
			return storages
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_all_net():
		try:
			networks = []
			for name in conn.listNetworks():
				networks.append(name)
			for name in conn.listDefinedNetworks():
				networks.append(name)
			# Not support all distro but Fedora!!!
			#for ifcfg in conn.listInterfaces():
			#	if ifcfg != 'lo' and not re.findall("eth", ifcfg):
			#		networks.append(ifcfg)
			#for ifcfg in conn.listDefinedInterfaces():
			#	if ifcfg != 'lo' and not re.findall("eth", ifcfg):
			#		networks.append(ifcfg)
			return networks
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"
	
	def find_all_iso():
		try:
			iso = []
			for storage in storages:
				stg = conn.storagePoolLookupByName(storage)
				stg.refresh(0)
				for img in stg.listVolumes():
					if re.findall(".iso", img) or re.findall(".ISO", img):
						iso.append(img)
			return iso
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def find_all_img():
		try:		
			disk = []
			for storage in storages:
				stg = conn.storagePoolLookupByName(storage)
				stg.refresh(0)
				for img in stg.listVolumes():
					if re.findall(".img", img) or re.findall(".IMG", img):
						disk.append(img)
			return disk
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"
	
	def get_img_path(vol):
		try:
			for storage in storages:
				stg = conn.storagePoolLookupByName(storage)
				for img in stg.listVolumes():
					if vol == img:
						vl = stg.storageVolLookupByName(vol)
						return vl.path()
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_img_format(vol):
		try:
			for storage in storages:
				stg = conn.storagePoolLookupByName(storage)
				for img in stg.listVolumes():
					if vol == img:
						vl = stg.storageVolLookupByName(vol)
						xml = vl.XMLDesc(0)
						format = util.get_xml_path(xml, "/volume/target/format/@type")
						return format
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_cpus():
		try:
			return conn.getInfo()[2]
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"
	
	def get_mem():
		try:
			return conn.getInfo()[1]
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_emulator():
		try:
			emulator = []
			xml = conn.getCapabilities()
			arch = conn.getInfo()[0]
			if arch == 'x86_64':
				emulator.append(util.get_xml_path(xml,"/capabilities/guest[1]/arch/emulator"))
				emulator.append(util.get_xml_path(xml,"/capabilities/guest[2]/arch/emulator"))
			else:
				emulator = util.get_xml_path(xml,"/capabilities/guest/arch/emulator")
			return emulator
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_machine():
		try:
			xml = conn.getCapabilities()
			machine = util.get_xml_path(xml,"/capabilities/guest/arch/machine/@canonical")
			return machine
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"
			
	def create_volume(stg_pool, img, size_max):
		try:
			size_max = int(size_max) * 1073741824
			xml = """
				<volume>
					<name>%s.img</name>
					<capacity>%s</capacity>
					<allocation>0</allocation>
					<target>
						<format type='qcow2'/>
					</target>
				</volume>""" % (img, size_max)
			stg = conn.storagePoolLookupByName(stg_pool)
			stg.createXML(xml,0)
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"
	
	def add_vm(name, mem, cpus, machine, emul, img, iso, bridge):
		try:
			arch = conn.getInfo()[0]
			if not iso:
				iso = ''
			memaloc = mem
			xml = """<domain type='kvm'>
					  <name>%s</name>
					  <memory>%s</memory>
					  <currentMemory>%s</currentMemory>
					  <vcpu>%s</vcpu>
					  <os>
					    <type arch='%s' machine='%s'>hvm</type>
					    <boot dev='hd'/>
					    <boot dev='cdrom'/>
					    <bootmenu enable='yes'/>
					  </os>
					  <features>
					    <acpi/>
					    <apic/>
					    <pae/>
					  </features>
					  <clock offset='utc'/>
					  <on_poweroff>destroy</on_poweroff>
					  <on_reboot>restart</on_reboot>
					  <on_crash>restart</on_crash>
					  <devices>""" % (name, mem, memaloc, cpus, arch, machine)
				
			if arch == 'x86_64':
				xml += """<emulator>%s</emulator>""" % (emul[1])
			else:
				xml += """<emulator>%s</emulator>""" % (emul)

			xml += """<disk type='file' device='disk'>
					      <driver name='qemu' type='qcow2'/>
					      <source file='%s'/>
					      <target dev='hda' bus='ide'/>
					    </disk>
					    <disk type='file' device='cdrom'>
					      <driver name='qemu' type='raw'/>
					      <source file='%s'/>
					      <target dev='hdc' bus='ide'/>
					      <readonly/>
					    </disk>
					    <controller type='ide' index='0'>
					      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
					    </controller>
					    """ % (img, iso)

			if re.findall("br", bridge):
				xml += """<interface type='bridge'>
						<source bridge='%s'/>""" % (bridge)
			else:
				xml += """<interface type='network'>
						<source network='%s'/>""" % (bridge)
				
			xml += """<address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
					    </interface>
					    <input type='tablet' bus='usb'/>
					    <input type='mouse' bus='ps2'/>
					    <graphics type='vnc' port='-1' autoport='yes'/>
					    <video>
					      <model type='cirrus' vram='9216' heads='1'/>
					      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
					    </video>
					    <memballoon model='virtio'>
					      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>
					    </memballoon>
					  </devices>
					</domain>"""
			conn.defineXML(xml)
			dom = conn.lookupByName(name)
			dom.setAutostart(1)
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	conn = vm_conn()

	if conn == "error":
		return HttpResponseRedirect('/overview/' + host_id + '/')

	errors = []
	cores = get_cpus()
	all_vm = get_all_vm()
	storages = get_all_stg()
	all_iso = find_all_iso()
	all_img = find_all_img()
	if all_iso is "error" or all_img is "error":
		msg = _('Storage pools are not available or are not active')
		errors.append(msg)	
	bridge = get_all_net()
	if bridge == "error":
		msg = _('Network pools are not available or are not active')
		errors.append(msg)			
	emul = get_emulator()
	machine = get_machine()
	addmem = get_mem()
	
	cpus = []
	for cpu in range(1,cores+1):
		cpus.append(cpu)

	if request.method == 'POST':
		name = request.POST.get('name','')
		setmem = request.POST.get('memory','')
		cpus = request.POST.get('cpus','')
		iso = request.POST.get('iso','')		
		img = request.POST.get('img','')
		netbr = request.POST.get('bridge','')
		setmem = int(setmem) * 1024
		hdd = get_img_path(img)
		cdrom = get_img_path(iso)
		hdd_frmt = get_img_format(img)
		simbol = re.search('[^a-zA-Z0-9\_]+', name)
		if name in all_vm:
			msg = _('This is the name of the virtual machine already exists')
			errors.append(msg)
		if len(name) > 20:
			msg = _('The name of the virtual machine must not exceed 20 characters')
			errors.append(msg)
		if simbol:
			msg = _('The name of the virtual machine must not contain any characters and Russian characters')
			errors.append(msg)
		if not request.POST.get('hdd','') and not img or img == 'error':
			msg = _('Images of the HDD to a virtual machine not available. You need to create an HDD image')
			errors.append(msg)
		if not name:
			msg = _('Enter the name of the virtual machine')
			errors.append(msg)
		if not errors:
			if request.POST.get('hdd',''):
				size = request.POST.get('hdd','')
				stg_pool = request.POST.get('stg_pool','')
				create_volume(stg_pool, name, size)
				img = name + '.img'
				hdd = get_img_path(img)
			if add_vm(name, setmem, cpus, machine, emul, hdd, cdrom, netbr) is 'error':
				msg = _('Hardware acceleration is not found')
				errors.append(msg)
			else:
				msg = _('Creating a virtual machine: ')
				msg = msg + name
				add_error(msg,'user')
				return HttpResponseRedirect('/vm/%s/%s/' % (host_id, name))


	conn.close()

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

Example 66

Project: hue
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.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 67

Project: tendenci
Source File: views.py
View license
@permission_required('theme_editor.change_themefileversion')
def edit_file(request, form_class=FileForm, template_name="theme_editor/index.html"):

    if not has_perm(request.user, 'theme_editor.view_themefileversion'):
        raise Http403

    selected_theme = request.GET.get("theme_edit", get_theme())
    original_theme_root = os.path.join(settings.ORIGINAL_THEMES_DIR, selected_theme)
    if settings.USE_S3_THEME:
        theme_root = os.path.join(settings.THEME_S3_PATH, selected_theme)
    else:
        theme_root = os.path.join(settings.ORIGINAL_THEMES_DIR, selected_theme)

    # get the default file and clean up any input
    default_file = request.GET.get("file", DEFAULT_FILE)

    if default_file:
        default_file = default_file.replace('\\', '/')
        default_file = default_file.strip('/')
        default_file = default_file.replace('////', '/')
        default_file = default_file.replace('///', '/')
        default_file = default_file.replace('//', '/')

    is_file = qstr_is_file(default_file, ROOT_DIR=theme_root)
    is_dir = qstr_is_dir(default_file, ROOT_DIR=theme_root)

    if is_file:
        pass
    elif is_dir:
        # if default_file is a directory then append the
        # trailing slash so we can get the dirname below
        default_file = '%s/' % default_file
    else:
        # if the default_file is not a directory or file within
        # the themes folder then return a 404
        raise Http404(_("Custom template not found. Make sure you've copied over the themes to the THEME_DIR."))

    # get the current file name
    current_file = os.path.basename(default_file)

    # get file ext
    name = current_file.split('/')[-1]
    ext = name.split('.')[-1]
    stylesheets = ['css', 'less']

    # get the present working directory
    # and make sure they cannot list root
    pwd = os.path.dirname(default_file)
    if pwd == '/':
        pwd = ''

    current_file_path = os.path.join(pwd, current_file)

    # get the previous directory name and path
    prev_dir = '/'
    prev_dir_name = 'theme base'
    pwd_split = pwd.split('/')
    if len(pwd_split) > 1:
        prev_dir_name = pwd_split[-2]
        pwd_split.pop()
        prev_dir = '/'.join(pwd_split)
    elif not pwd_split[0]:
        prev_dir = ''

    # get the direcory list
    dirs = get_dir_list(pwd, ROOT_DIR=theme_root)

    # get the file list
    files, non_editable_files = get_file_list(pwd, ROOT_DIR=theme_root)

    all_files_folders = get_all_files_list(ROOT_DIR=theme_root)

    # non-deletable files
    non_deletable_files = ['homepage.html', 'default.html', 'footer.html', 'header.html', 'sidebar.html', 'nav.html', 'styles.less', 'styles.css']

    # get the number of themes in the themes directory on the site
    theme_choices = [ i for i in theme_choice_list()]
    theme_count = len(theme_choices)

    # get a list of revisions
    archives = ThemeFileVersion.objects.filter(relative_file_path=default_file).order_by("-create_dt")

    if request.is_ajax() and request.method == "POST":
        file_form = form_class(request.POST)
        response_status = 'FAIL'
        response_message = _('Cannot update file.')
        if file_form.is_valid():
            if file_form.save(request, default_file, ROOT_DIR=theme_root, ORIG_ROOT_DIR=original_theme_root):
                response_status = 'SUCCESS'
                response_message = unicode(_('Your changes have been saved.'))
                EventLog.objects.log()

        response = json.dumps({'status':response_status, 'message':response_message})
        return HttpResponse(response, content_type="application/json")

    content = get_file_content(default_file,  ROOT_DIR=theme_root)
    file_form = form_class({"content": content, "rf_path": default_file})

    theme_form = ThemeSelectForm(initial={'theme_edit': selected_theme})

    return render_to_response(template_name, {
        'file_form': file_form,
        'theme_form': theme_form,
        'current_theme': selected_theme,
        'current_file_path': current_file_path,
        'current_file': current_file,
        'prev_dir_name': prev_dir_name,
        'prev_dir': prev_dir,
        'pwd': pwd,
        'dirs': dirs,
        'files': files,
        'non_editable_files': non_editable_files,
        'non_deletable_files': non_deletable_files,
        'theme_count': theme_count,
        'archives': archives,
        'is_file': is_file,
        'is_dir': is_dir,
        'all_files_folders': all_files_folders,
        'ext' : ext,
        'stylesheets' : stylesheets
    }, context_instance=RequestContext(request))

Example 68

Project: decode-Django
Source File: views.py
View license
@staff_member_required
def model_detail(request, app_label, model_name):
    if not utils.docutils_is_available:
        return missing_docutils_page(request)

    # Get the model class.
    try:
        app_mod = models.get_app(app_label)
    except ImproperlyConfigured:
        raise Http404(_("App %r not found") % app_label)
    model = None
    for m in models.get_models(app_mod):
        if m._meta.object_name.lower() == model_name:
            model = m
            break
    if model is None:
        raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % {'model_name': model_name, 'app_label': app_label})

    opts = model._meta

    # Gather fields/field descriptions.
    fields = []
    for field in opts.fields:
        # ForeignKey is a special case since the field will actually be a
        # descriptor that returns the other object
        if isinstance(field, models.ForeignKey):
            data_type = field.rel.to.__name__
            app_label = field.rel.to._meta.app_label
            verbose = utils.parse_rst((_("the related `%(app_label)s.%(data_type)s` object")  % {'app_label': app_label, 'data_type': data_type}), 'model', _('model:') + data_type)
        else:
            data_type = get_readable_field_data_type(field)
            verbose = field.verbose_name
        fields.append({
            'name': field.name,
            'data_type': data_type,
            'verbose': verbose,
            'help_text': field.help_text,
        })

    # Gather many-to-many fields.
    for field in opts.many_to_many:
        data_type = field.rel.to.__name__
        app_label = field.rel.to._meta.app_label
        verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': app_label, 'object_name': data_type}
        fields.append({
            'name': "%s.all" % field.name,
            "data_type": 'List',
            'verbose': utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name),
        })
        fields.append({
            'name'      : "%s.count" % field.name,
            'data_type' : 'Integer',
            'verbose'   : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name),
        })

    # Gather model methods.
    for func_name, func in model.__dict__.items():
        if (inspect.isfunction(func) and len(inspect.getargspec(func)[0]) == 1):
            try:
                for exclude in MODEL_METHODS_EXCLUDE:
                    if func_name.startswith(exclude):
                        raise StopIteration
            except StopIteration:
                continue
            verbose = func.__doc__
            if verbose:
                verbose = utils.parse_rst(utils.trim_docstring(verbose), 'model', _('model:') + opts.module_name)
            fields.append({
                'name': func_name,
                'data_type': get_return_data_type(func_name),
                'verbose': verbose,
            })

    # Gather related objects
    for rel in opts.get_all_related_objects() + opts.get_all_related_many_to_many_objects():
        verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': rel.opts.app_label, 'object_name': rel.opts.object_name}
        accessor = rel.get_accessor_name()
        fields.append({
            'name'      : "%s.all" % accessor,
            'data_type' : 'List',
            'verbose'   : utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name),
        })
        fields.append({
            'name'      : "%s.count" % accessor,
            'data_type' : 'Integer',
            'verbose'   : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name),
        })
    return render_to_response('admin_doc/model_detail.html', {
        'root_path': urlresolvers.reverse('admin:index'),
        'name': '%s.%s' % (opts.app_label, opts.object_name),
        'summary': _("Fields on %s objects") % opts.object_name,
        'description': model.__doc__,
        'fields': fields,
    }, context_instance=RequestContext(request))

Example 69

Project: readthedocs.org
Source File: views.py
View license
def create_profile(request, form_class, success_url=None,
                   template_name='profiles/private/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, a redirect will be issued to the
    :view:`profiles.views.edit_profile` view.

    **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.

    ``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.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 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 70

Project: storyboard
Source File: views.py
View license
@login_required      
def upload(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            if request.FILES.has_key('images'):
                name = request.FILES['images'].name
                content_type = request.FILES['images'].content_type or 'application/octet-stream'#'text/plain'
                file_data = request.FILES['images'].read()
                
                now = datetime.datetime.now()

                file_ext_pos = name.rfind('.')
                file_name_len = len(name)

                if not (content_type == 'image/jpeg' or content_type == 'image/png' or content_type == 'image/gif'):
                    return
                if file_ext_pos<=0 and file_ext_pos>=file_name_len:
                    return
                file_ext = name[file_ext_pos-file_name_len:].lower()
                file_uri  = '%s%s' % (now.strftime('%Y-%m-%d-%H%M%S-%f'),file_ext)          
                file_name = 'uploads/ohbug/photo/%s%s' % (now.strftime('%Y-%m/%d-%H%M%S-%f'),file_ext)
                file_path = '/%s/%s/%s' % (STORAGE_SERVICE,STORAGE_BUCKET,file_name)

                if STORAGE_SERVICE == 'sina':
                    import sae.storage
                    s = sae.storage.Client()
                    ob = sae.storage.Object(file_data,expires='', content_type=content_type, content_encoding='gzip')
                    s.put(STORAGE_BUCKET, file_uri , ob)
                    file_name = file_uri

                if STORAGE_SERVICE == 'baidu':
                    # TMPDIR = '/tmp'
                    # try:
                    #     from bae.core import const
                    #     TMPDIR = const.APP_TMPDIR
                    # except Exception, e:
                    #     pass
                    # output = open(TMPDIR+'/'+file_uri, 'wb')
                    # output.write(file_data)
                    # output.close()
                    # try:
                    #   from bae.api import logging as logger
                    # except:
                    #   import logging
                    #   logger = logging.getLogger('pyhttpclient')
                    # logger.info('file_data')
                    # logger.info(file_uri)
                    # BAE API
                    # from bae.api import bcs
                    # baebcs = bcs.BaeBCS('http://bcs.duapp.com/', STORAGE_ACCESS_KEY, STORAGE_SECRET_ACCESS_KEY)
                    # #obj_path = TMPDIR+'/'+file_uri
                    # obj_name = u'/%s'%(file_uri)
                    # baebcs.put_object(STORAGE_BUCKET, obj_name.encode('utf8'), file_data)
                    # #baebcs.put_file(STORAGE_BUCKET, obj_name.encode('utf8'), obj_path.encode('utf8'))
                    # baebcs.make_public(STORAGE_BUCKET, obj_name.encode('utf8'))

                    # BCS API
                    import pybcs
                    # # TMPDIR = '/tmp'
                    # # try:
                    # #     from bae.core import const
                    # #     TMPDIR = const.APP_TMPDIR
                    # # except Exception, e:
                    # #     pass
                    # # output = open(TMPDIR+'/'+file_uri, 'wb')
                    # # output.write(file_data)
                    # # output.close()
                    bcs = pybcs.BCS('http://bcs.duapp.com/', STORAGE_ACCESS_KEY, STORAGE_SECRET_ACCESS_KEY)
                    bucket = bcs.bucket(STORAGE_BUCKET)
                    obj_name = u'/%s'%(file_uri)
                    obj = bucket.object(obj_name.encode('utf8'))
                    obj.put(file_data)
                    obj.make_public()
                    #obj.put_file(TMPDIR+'/'+file_uri)
                    file_name = file_uri

                # Google Storage
                if STORAGE_SERVICE == 'gs':
                    dst_uri = boto.storage_uri(STORAGE_BUCKET, STORAGE_SERVICE)
                    
                    new_dst_uri = dst_uri.clone_replace_name(file_name)
                    #logging.info(dst_uri)
                    #logging.info(new_dst_uri)
                    tmp = tempfile.TemporaryFile()
                    tmp.write(file_data)
                    tmp.seek(0)
                    dst_key = new_dst_uri.new_key()
                    dst_key.content_type = content_type
                    dst_key.set_contents_from_file(tmp)
                    #logger.info('hello')
                    
                    # write_path = files.gs.create(file_path, acl='bucket-owner-full-control',mime_type=content_type)
                    # with files.open(write_path, 'a') as fp:
                    #     fp.write(file_data)
                    # files.finalize(write_path)

                s = Storage()
                s.storage  = STORAGE_SERVICE
                s.bucket  = STORAGE_BUCKET
                s.path = file_name
                s.mime = content_type
                s.size = len(file_data)
                s.md5 = hashlib.md5(file_data).hexdigest()
                s.name = name
                s.kind = 'image'
                s.author = request.user
                s.save()
                return HttpResponseRedirect('/photo/%s'%s.key)
    else:
        form = UploadForm()
    return render_to_response('storage/upload.html',{'form':form},context_instance=RequestContext(request))

Example 71

Project: hubplus
Source File: views.py
View license
@secure_resource(TgGroup)
def group(request, group, template_name="plus_groups/group.html", current_app='plus_groups', **kwargs):

    if not group :
        raise Http404(_('There is no group with this id'))

    user = request.user

    can_join = False
    apply = False
    leave = False
    invite = False
    can_comment = False
    message = False
    add_link = False
    can_tag = False
    can_change_avatar = False
    has_accept = False
    can_delete = False

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

    editable_group_type = group.group_type != settings.GROUP_HUB_TYPE

    if user.is_authenticated():
        if user.is_direct_member_of(group.get_inner()):
            # can now leave group if you aren't the last one out
            if group.get_no_members() > 1 :
                leave = True
            try :
                group.invite_member
                invite = True
            except Exception, e :# user doesn't have invite permission
                pass

        else :
            try :
                group.join 
                can_join = True
            except Exception, e: # user doesn't have join permission
                pass
            try :
                if not can_join :
                    group.apply
                    apply = True
            except Exception, e : # user doesn't have apply permission
                pass

        try : 
            group.comment
            can_comment = True
            can_tag = True # XXX commentor interface governs who can tag. Do we need a special tag interface?
        except :
            pass


        try :
            group.message_members
            message = True
        except :
            pass
        
        try :
            group.create_Link
            add_link = True
        except Exception, e :
            print e
            pass

        try :
            group.change_avatar
            can_change_avatar  = True
        except Exception, e:
            pass

        try :
            dummy = group.delete
            can_delete = True
        except :
            pass

        if has_access(request.user, None, 'Application.Accept', group._inner.get_security_context()):
            has_accept = True
        else:
            has_accept = False
    
    tweets = FeedItem.feed_manager.get_from_permissioned(group, request.user)

    try:
        group.get_all_sliders
        perms_bool = True
    except PlusPermissionsNoAccessException:
        perms_bool = False

    if kwargs['type'] == 'hub':
        type_name = hub_name()
    else:
        type_name = "Group"

    search_types = narrow_search_types(type_name)
    side_search = side_search_args(current_app + ':groups', search_types[0][1][2])

    search = request.GET.get('search', '')
    order = request.GET.get('order', '')
    resource_search = resources(group=group, search=search, order=order)
    resource_listing_args = listing_args(current_app + ':group_resources', current_app + ':group_resources_tag', tag_string='', search_terms=search, multitabbed=False, order=order, template_base='plus_lib/listing_frag.html', search_type_label='resources')
    resource_listing_args['group_id'] = group.id

    ##############Here we should use the "plus_search" function from plus_explore as above########

    member_search = a_member_search(group=group, search=search, order=order, 
                                    member_profile_ids=[x.get_profile().get_ref().id for x in group.users.all()])
    host_search = a_member_search(group=group.get_admin_group(), search=search, order=order, 
                                  member_profile_ids=[x.get_profile().get_ref().id for x in group.get_admin_group().users.all()])
    member_listing_args = listing_args(current_app+':group_members', current_app+':group_members_tag', tag_string='', search_terms=search, multitabbed=False, order=order, template_base='plus_lib/listing_frag.html', search_type_label='members', group_id=group.id)

    host_listing_args = listing_args(current_app+':group_hosts', current_app+':group_hosts_tag', tag_string='', search_terms=search, multitabbed=False, order=order, template_base='plus_lib/listing_frag.html', search_type_label='hosts', group_id=group.id)
    member_count = group.users.all().count()
    host_count = group.get_admin_group().users.all().count()


    ##############################################################################################

    return render_to_response(template_name, {
            "head_title" : "%s" % group.get_display_name(),
            "status_type" : 'group',
            #"status_since" : status_since,
            "group" : TemplateSecureWrapper(group),
            "target_class" : ContentType.objects.get_for_model(group.get_inner()).id,
            "target_id" : group.get_inner().id,
            #"members" : members,
            "member_count" : member_count,
            "leave": leave,
            "can_join" : can_join, 
            "apply" : apply, 
            "invite" : invite, 
            "can_comment" : can_comment, 
            "message" : message,
            "add_link" : add_link,
            "can_tag" : can_tag,
            "can_change_avatar" : can_change_avatar,
            "can_delete" : can_delete, 

            "is_following" : is_following,
            #"hosts": hosts,
            "host_group_id":group.get_admin_group().id,
            "host_group_app_label":group.get_admin_group().group_app_label() + ':group',
            "is_host":user.is_admin_of(group.get_inner()),
            "host_count": host_count,
            "tweets" : tweets,
            "permissions": perms_bool,
            'side_search_args':side_search,
            'resource_search':resource_search,
            'resource_listing_args':resource_listing_args,
            'member_search':member_search,
            'member_listing_args':member_listing_args,
            'host_search':host_search,
            'host_listing_args':host_listing_args,
            'group_id':group.id,
            'search_types':search_types,
            'tagged_url':current_app + ':groups_tag',
            'has_accept':has_accept,
            'editable_group_type':editable_group_type,
            }, context_instance=RequestContext(request, current_app=current_app)
    )

Example 72

Project: CuckooSploit
Source File: views.py
View license
def search(request):
    if "search" in request.POST:
        error = None

        try:
            term, value = request.POST["search"].strip().split(":", 1)
        except ValueError:
            term = ""
            value = request.POST["search"].strip()

        if term:
            # Check on search size.
            if len(value) < 3:
                return render_to_response("analysis/search.html",
                                          {"analyses": None,
                                           "term": request.POST["search"],
                                           "error": "Search term too short, minimum 3 characters required"},
                                          context_instance=RequestContext(request))
            # name:foo or name: foo
            value = value.lstrip()

            # Search logic.
            if term == "name":
                records = results_db.analysis.find({"target.file.name": {"$regex": value, "$options": "-i"}}).sort([["_id", -1]])
            elif term == "type":
                records = results_db.analysis.find({"target.file.type": {"$regex": value, "$options": "-i"}}).sort([["_id", -1]])
            elif term == "string":
                records = results_db.analysis.find({"strings" : {"$regex" : value, "$options" : "-1"}}).sort([["_id", -1]])
            elif term == "ssdeep":
                records = results_db.analysis.find({"target.file.ssdeep": {"$regex": value, "$options": "-i"}}).sort([["_id", -1]])
            elif term == "crc32":
                records = results_db.analysis.find({"target.file.crc32": value}).sort([["_id", -1]])
            elif term == "file":
                records = results_db.analysis.find({"behavior.summary.files": {"$regex": value, "$options": "-i"}}).sort([["_id", -1]])
            elif term == "key":
                records = results_db.analysis.find({"behavior.summary.keys": {"$regex": value, "$options": "-i"}}).sort([["_id", -1]])
            elif term == "mutex":
                records = results_db.analysis.find({"behavior.summary.mutexes": {"$regex": value, "$options": "-i"}}).sort([["_id", -1]])
            elif term == "domain":
                records = results_db.analysis.find({"network.domains.domain": {"$regex": value, "$options": "-i"}}).sort([["_id", -1]])
            elif term == "ip":
                records = results_db.analysis.find({"network.hosts": value}).sort([["_id", -1]])
            elif term == "signature":
                records = results_db.analysis.find({"signatures.description": {"$regex": value, "$options": "-i"}}).sort([["_id", -1]])
            elif term == "url":
                records = results_db.analysis.find({"target.url": value}).sort([["_id", -1]])
            elif term == "imphash":
                records = results_db.analysis.find({"static.pe_imphash": value}).sort([["_id", -1]])
            else:
                return render_to_response("analysis/search.html",
                                          {"analyses": None,
                                           "term": request.POST["search"],
                                           "error": "Invalid search term: %s" % term},
                                          context_instance=RequestContext(request))
        else:
            value = value.lower()

            if re.match(r"^([a-fA-F\d]{32})$", value):
                records = results_db.analysis.find({"target.file.md5": value}).sort([["_id", -1]])
            elif re.match(r"^([a-fA-F\d]{40})$", value):
                records = results_db.analysis.find({"target.file.sha1": value}).sort([["_id", -1]])
            elif re.match(r"^([a-fA-F\d]{64})$", value):
                records = results_db.analysis.find({"target.file.sha256": value}).sort([["_id", -1]])
            elif re.match(r"^([a-fA-F\d]{128})$", value):
                records = results_db.analysis.find({"target.file.sha512": value}).sort([["_id", -1]])
            else:
                return render_to_response("analysis/search.html",
                                          {"analyses": None,
                                           "term": None,
                                           "error": "Unable to recognize the search syntax"},
                                          context_instance=RequestContext(request))

        # Get data from cuckoo db.
        db = Database()
        analyses = []

        for result in records:
            new = db.view_task(result["info"]["id"])

            if not new:
                continue

            new = new.to_dict()

            if result["info"]["category"] == "file":
                if new["sample_id"]:
                    sample = db.view_sample(new["sample_id"])
                    if sample:
                        new["sample"] = sample.to_dict()

            analyses.append(new)

        return render_to_response("analysis/search.html",
                                  {"analyses": analyses,
                                   "term": request.POST["search"],
                                   "error": None},
                                  context_instance=RequestContext(request))
    else:
        return render_to_response("analysis/search.html",
                                  {"analyses": None,
                                   "term": None,
                                   "error": None},
                                  context_instance=RequestContext(request))

Example 73

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 74

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 75

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 76

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 77

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 78

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 79

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 80

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 81

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 82

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 83

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 84

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 85

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 86

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 87

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 88

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 89

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 90

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 91

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 92

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 93

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 94

Project: django-wikiapp
Source File: views.py
View license
@login_required
def edit_article(request, title,
                 group_slug=None, bridge=None,
                 article_qs=ALL_ARTICLES,
                 ArticleClass=Article, # to get the DoesNotExist exception
                 ArticleFormClass=ArticleForm,
                 template_name='edit.html',
                 template_dir='wiki',
                 extra_context=None,
                 check_membership=False,
                 is_member=None,
                 is_private=None,
                 *args, **kw):

    if group_slug is not None:
        try:
            group = bridge.get_group(group_slug)
        except ObjectDoesNotExist:
            raise Http404
        allow_read = has_read_perm(request.user, group, is_member,
                                   is_private)
        allow_write = has_write_perm(request.user, group, is_member)
    else:
        group = None
        allow_read = allow_write = True


    if not allow_write:
        return HttpResponseForbidden()

    try:
        article = article_qs.get_by(title, group)
    except ArticleClass.DoesNotExist:
        article = None

    if request.method == 'POST':

        form = ArticleFormClass(request.POST, instance=article)

        if form.is_valid():

            if request.user.is_authenticated():
                form.editor = request.user
                if article is None:
                    user_message = u"Your article was created successfully."
                else:
                    user_message = u"Your article was edited successfully."
                request.user.message_set.create(message=user_message)

            if ((article is None) and (group_slug is not None)):
                form.group = group

            new_article, changeset = form.save()
            
            url = get_url('wiki_article', group, kw={
                'title': new_article.title,
            }, bridge=bridge)
            
            return redirect_to(request, url)

    elif request.method == 'GET':
        user_ip = get_real_ip(request)

        lock = cache.get(title, None)
        if lock is None:
            lock = ArticleEditLock(title, request)
        lock.create_message(request)

        initial = {'user_ip': user_ip}
        if group_slug is not None:
            # @@@ wikiapp currently handles the group filtering, but we will
            # eventually want to handle that via the bridge.
            initial.update({'content_type': get_ct(group).id,
                            'object_id': group.id})

        if article is None:
            initial.update({'title': title,
                            'action': 'create'})
            form = ArticleFormClass(initial=initial)
        else:
            initial['action'] = 'edit'
            form = ArticleFormClass(instance=article,
                                    initial=initial)

    template_params = {'form': form}

    if group_slug is not None:
        template_params['group'] = group
    if extra_context is not None:
        template_params.update(extra_context)

    return render_to_response(os.path.join(template_dir, template_name),
                              template_params,
                              context_instance=RequestContext(request))

Example 95

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 96

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 97

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 98

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 99

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 100

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))