Python django.shortcuts 模块,render_to_response() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.shortcuts.render_to_response()

项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def index(request):
    if request.method == 'POST':
        form = PathAnalysisForm(request.POST)
        if  form.is_valid():
            query = form.cleaned_data['search']
            print(query)
            #here is where the magic happens!
            #search in kegg
#            data = kegg_rest_request('list/pathway/hsa')
#            pathways = kegg_rest_request('find/pathway/%s' % (query))
            pathways = Pathway.objects.filter(Q(name__icontains=query))
            # print pathways

    else:
        form = PathAnalysisForm()
#        pathways = kegg_rest_request('list/pathway/hsa')
        pathways = Pathway.objects.all()    


    return render_to_response('pathway_analysis/index.html', {'form': form, 'pathways': pathways}, context_instance=RequestContext(request))
项目:django-ajax-views    作者:Pyco7    | 项目源码 | 文件源码
def _date_filter_response(self, field):
        query_dict = self._get_queryset_all().aggregate(Min(field), Max(field))
        min_date = query_dict[field + '__min']
        max_date = query_dict[field + '__max']
        if isinstance(min_date, datetime.datetime):
            min_date = min_date.date()
        if isinstance(max_date, datetime.datetime):
            max_date = max_date.date()

        selected_dates = self.json_cfg.get('selected_filter_values', None)
        if selected_dates and not self.json_cfg.get('ignore_selected_values', False):
            selected_min_date = parse(selected_dates['min_date']).date()
            selected_max_date = parse(selected_dates['max_date']).date()
            reset_button = True
        else:
            selected_min_date = min_date
            selected_max_date = max_date
            reset_button = False
        return render_to_response('ajaxviews/_select_date_filter.html', {
            'min_date': min_date,
            'max_date': max_date,
            'selected_min_date': selected_min_date,
            'selected_max_date': selected_max_date,
            'reset_button': reset_button,
        })
项目:lushi8    作者:ieiayaobb    | 项目源码 | 文件源码
def get_index(request):
    # response = requests.get('http://127.0.0.1:8000/api/chairmans/')
    # chairmans = response.json()

    if 'type' in request.GET:
        type = request.GET['type']
        chairmans = Chairman.objects.filter(type=type).order('-num')
    else:
        chairmans = Chairman.objects.all().order('-num')

    # chairmans_set = SortedSet('chairmans_set')
    # chairmans_hash = SortedSet('chairmans_hash')
    # chairmans = map(_convert_chairman, chairmans_set.revmembers)
    # chairmans = map(_convert_chairman, chairmans_hash.members)

    return render_to_response('index.html', locals(),
                              context_instance=RequestContext(request))
项目:lushi8    作者:ieiayaobb    | 项目源码 | 文件源码
def fetch(request):
    fetcher = Fetcher()
    fetcher.fetch_cc()
    fetcher.fetch_douyu()
    fetcher.fetch_longzhu()
    fetcher.fetch_quanmin()
    fetcher.fetch_xiongmao()
    fetcher.fetch_zhanqi()
    fetcher.fetch_huya()

    # chairmans_set = SortedSet('chairmans_set')
    # charimans_hash = Hash('chairmans_hash')
    for chairman in fetcher.chairmans:
        try:
            if chairman.is_valid():
                # charimans_hash[chairman.id] = chairman
                # chairmans_set.add(chairman, chairman.num)
                chairman.save()
            else:
                print chairman.errors
        except Exception, e:
            print e

    return render_to_response('index.html', locals(),
                              context_instance=RequestContext(request))
项目:pdpdmeetup    作者:mattharley    | 项目源码 | 文件源码
def home_page(request):
    try:
        coming_event = get_events('upcoming')[0]
    except IndexError:
        coming_event = {
            'event_name': 'No upcoming event',
            'event_description': 'Check back in the middle of the month',
            'og_event_description': 'Check back in the middle of the month',
        }
    return render_to_response(
        'home.html',
        {
            'coming_event': coming_event, 
        },
        # context_instance=RequestContext(request)
    )
项目:pdpdmeetup    作者:mattharley    | 项目源码 | 文件源码
def ajax_meetups_tab(request, event_status):
    """
    Queries the meetup.com API to get all the events of the status specified

    :param request:
    :param event_status: upcoming, past, proposed, suggested, cancelled, draft
    :return:
    """
    events = get_events(event_status)

    return render_to_response(
        'ajax/ajax_meetups.html',
        {
            "group_events": events,

            'event_status': event_status,
        })
项目:django-mako    作者:ahmedaljazzar    | 项目源码 | 文件源码
def function_based_view(request, engine):
    context = {
        'items': [
            'Wow',
            'This is awesome',
            'Don\'t forget to bring some bread honey ;)',
            'The requested template is: {}'.format(engine),
        ],
        'value': 1+1,
        'engine': engine,
    }

    if engine == 'mako':
        template_name = 'mako.html'
    else:
        template_name = 'django.html'

    return render_to_response(
        template_name=template_name,
        context=context,
        using=engine,
    )
项目:django-celery-monitor    作者:jezdez    | 项目源码 | 文件源码
def rate_limit_tasks(self, request, queryset):
        tasks = set([task.name for task in queryset])
        opts = self.model._meta
        app_label = opts.app_label
        if request.POST.get('post'):
            rate = request.POST['rate_limit']
            with current_app.default_connection() as connection:
                for task_name in tasks:
                    rate_limit(task_name, rate, connection=connection)
            return None

        context = {
            'title': _('Rate limit selection'),
            'queryset': queryset,
            'object_name': force_text(opts.verbose_name),
            'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
            'opts': opts,
            'app_label': app_label,
        }

        return render_to_response(
            self.rate_limit_confirmation_template, context,
            context_instance=RequestContext(request),
        )
项目:SPBU-DBMS-Project    作者:Betekhtin    | 项目源码 | 文件源码
def login(request):
    username = auth.get_user(request).username
    if (username):
        return redirect('/')
    else:
        args = {}
        args.update(csrf(request))
        if request.POST:
            username = request.POST.get('username','')
            password = request.POST.get('password','')
            user = auth.authenticate(username=username, password=password)
            if user is not None:
                if not request.POST.get('remember-me', ''):
                    request.session.set_expiry(0)
                auth.login(request, user)
                return redirect('/')
            else:
                args['login_error'] = format_html("<div class=\"main-error alert alert-error\">???????????? ??? ???????????? ??? ??????</div>")
                return render_to_response('login.html', args)
        else:
            return render_to_response('login.html', args)
项目:SPBU-DBMS-Project    作者:Betekhtin    | 项目源码 | 文件源码
def history(request):
    username = auth.get_user(request).username
    if (username):
        ?t = city.objects.all().values()
        co = country.objects.all().values()

        city_json = json.dumps(list(?t), cls=DjangoJSONEncoder,ensure_ascii=False)
        country_json = json.dumps(list(co), cls=DjangoJSONEncoder,ensure_ascii=False)
        args={}
        args['city']=city_json
        args['country'] = country_json
        args['max_date'] = []
        for i in ?t:
            args['max_date'].append((temperature.objects.filter(city_id__exact=i['city_id']).latest('date').date))
        return render_to_response("history.html",args)
    else:
        return redirect("/login")
项目:SPBU-DBMS-Project    作者:Betekhtin    | 项目源码 | 文件源码
def register(request):
    username = auth.get_user(request).username
    if not (username):
        args={}
        args.update(csrf(request))
        args['form']=UserCreationForm()
        if request.POST:
            newuser_form=UserCreationForm(request.POST)
            if newuser_form.is_valid():
                newuser_form.save()
                newuser = auth.authenticate(username=newuser_form.cleaned_data['username'],password=newuser_form.cleaned_data['password2'])
                auth.login(request, newuser)
                return redirect('/')
            else:
                args['errors'] = format_html('<div class="main-error alert alert-error">?????? ??? ???????????</div>')
                args['form'] = newuser_form
        return render_to_response('register.html',args)
    else:
        return redirect('/')
项目:VManagePlatform    作者:welliamcao    | 项目源码 | 文件源码
def addVmServer(request):
    if request.method == "GET":
        return render_to_response('vmServer/add_server.html',
                                  {"user":request.user,"localtion":[{"name":"??","url":'/'},{"name":"??????","url":'#'},{"name":"????","url":"/addServer"}]},
                                  context_instance=RequestContext(request))

    elif  request.method == "POST":
        try:     
            VmServer.objects.create(hostname=request.POST.get('hostname'),
                                    username=request.POST.get('username',None),
                                    vm_type=request.POST.get('vm_type'),
                                    server_ip=request.POST.get('server_ip'),
                                    passwd=request.POST.get('passwd',None),
                                    status=0,)
            return render_to_response('vmServer/add_server.html',
                                  {"user":request.user,"localtion":[{"name":"??","url":'/'},{"name":"??????","url":'#'},{"name":"????","url":"/addServer"}]},
                                  context_instance=RequestContext(request))
        except Exception,e:
            return render_to_response('vmServer/add_server.html',
                                  {"user":request.user,"localtion":[{"name":"??","url":'/'},{"name":"??????","url":'#'},{"name":"????","url":"/addServer"}],
                                   "errorInfo":e},
                                  context_instance=RequestContext(request))
项目:VManagePlatform    作者:welliamcao    | 项目源码 | 文件源码
def login(request):
    if request.session.get('username') is not None:
        return HttpResponseRedirect('/profile',{"user":request.user})
    else:
        username = request.POST.get('username')
        password = request.POST.get('password') 
        user = auth.authenticate(username=username,password=password)
        if user and user.is_active:
            auth.login(request,user)
            request.session['username'] = username
            return HttpResponseRedirect('/profile',{"user":request.user})
        else:
            if request.method == "POST":
                return render_to_response('login.html',{"login_error_info":"???????????????"},
                                                        context_instance=RequestContext(request))  
            else:
                return render_to_response('login.html',context_instance=RequestContext(request))
项目:VManagePlatform    作者:welliamcao    | 项目源码 | 文件源码
def listStorage(request,id):        
    if request.method == "GET":
        try:
            vServer = VmServer.objects.get(id=id)
        except Exception,e:
            return render_to_response('404.html',context_instance=RequestContext(request))
        try:
            VMS = LibvirtManage(vServer.server_ip,vServer.username, vServer.passwd, vServer.vm_type)
            SERVER = VMS.genre(model='server')
            if SERVER:
                storageList = SERVER.getVmStorageInfo()
                VMS.close()
            else:return render_to_response('404.html',context_instance=RequestContext(request))
        except Exception,e:
            return render_to_response('404.html',context_instance=RequestContext(request))        
        return render_to_response('vmStorage/list_storage.html',
                                  {"user":request.user,"localtion":[{"name":"??","url":'/'},{"name":"?????","url":'#'},
                                                                    {"name":"?????","url":"/listStorage/%d/" % vServer.id}],
                                    "vmServer":vServer,"storageList":storageList}, context_instance=RequestContext(request))
项目:VManagePlatform    作者:welliamcao    | 项目源码 | 文件源码
def viewStorage(request,id,name): 
    if request.method == "GET":
        try:
            vServer = VmServer.objects.get(id=id)
        except:
            return render_to_response('404.html',context_instance=RequestContext(request))        
        try:
            VMS = LibvirtManage(vServer.server_ip,vServer.username, vServer.passwd, vServer.vm_type)
            STORAGE = VMS.genre(model='storage')
            if STORAGE:
                storage = STORAGE.getStorageInfo(name)
                VMS.close()
            else:return render_to_response('404.html',context_instance=RequestContext(request))
        except Exception,e:
            return render_to_response('404.html',context_instance=RequestContext(request))    
        return render_to_response('vmStorage/view_storage.html',
                                  {"user":request.user,"localtion":[{"name":"??","url":'/'},{"name":"?????","url":'#'},
                                                                    {"name":"?????","url":"/listStorage/%d/" % vServer.id},
                                                                    {"name":"?????","url":"/viewStorage/%d/%s/" % (vServer.id,name)}],
                                    "vmServer":vServer,"storage":storage}, context_instance=RequestContext(request))
项目:VManagePlatform    作者:welliamcao    | 项目源码 | 文件源码
def tempInstance(request): 
    if request.method == "GET":  
        tempList = VmInstance_Template.objects.all()
        return render_to_response('vmInstance/temp_instance.html',
                                  {"user":request.user,"localtion":[{"name":"??","url":'/'},{"name":"????","url":'/tempInstance'}],
                                   "tempList":tempList},
                                  context_instance=RequestContext(request)) 
    elif request.method == "POST":
        op = request.POST.get('op')
        if op in ['add','modf','del'] and request.user.has_perm('VManagePlatform.add_vminstance_template'):
            if op == 'add':
                result = VmInstance_Template.objects.create(name=request.POST.get('name'),cpu=request.POST.get('cpu'),
                                                       mem=request.POST.get('mem'),disk=request.POST.get('disk'))
                if isinstance(result, str):return JsonResponse({"code":500,"data":result,"msg":"?????"})                   
                else:return JsonResponse({"code":200,"data":None,"msg":"?????"})
        else:return JsonResponse({"code":500,"data":None,"msg":"????????????????????"})
项目:pyt    作者:python-security    | 项目源码 | 文件源码
def task_edit(request, project_id, task_id):

    proj = Project.objects.get(pk=project_id)
    task = Task.objects.get(pk=task_id)

    if request.method == 'POST':

        if task.project == proj:

            text = request.POST.get('text', False)
            task_title = request.POST.get('task_title', False)
            task_completed = request.POST.get('task_completed', False)

            task.title = task_title
            task.text = text
            task.completed = True if task_completed == "1" else False
            task.save()

        return redirect('/taskManager/' + project_id + '/' + task_id)
    else:
        return render_to_response(
            'taskManager/task_edit.html', {'task': task}, RequestContext(request))
项目:pyt    作者:python-security    | 项目源码 | 文件源码
def task_edit(request, project_id, task_id):

    proj = Project.objects.get(pk=project_id)
    task = Task.objects.get(pk=task_id)

    if request.method == 'POST':

        if task.project == proj:

            text = request.POST.get('text', False)
            task_title = request.POST.get('task_title', False)
            task_completed = request.POST.get('task_completed', False)

            task.title = task_title
            task.text = text
            task.completed = True if task_completed == "1" else False
            task.save()

        return redirect('/taskManager/' + project_id + '/' + task_id)
    else:
        return render_to_response(
            'taskManager/task_edit.html', {'task': task}, RequestContext(request))

# A4: Insecure Direct Object Reference (IDOR)
项目:pyt    作者:python-security    | 项目源码 | 文件源码
def project_edit(request, project_id):

    proj = Project.objects.get(pk=project_id)

    if request.method == 'POST':

        title = request.POST.get('title', False)
        text = request.POST.get('text', False)
        project_priority = int(request.POST.get('project_priority', False))
        project_duedate = datetime.datetime.fromtimestamp(
            int(request.POST.get('project_duedate', False)))

        proj.title = title
        proj.text = text
        proj.priority = project_priority
        proj.due_date = project_duedate
        proj.save()

        return redirect('/taskManager/' + project_id + '/')
    else:
        return render_to_response(
            'taskManager/project_edit.html', {'proj': proj}, RequestContext(request))

# A4: Insecure Direct Object Reference (IDOR)
项目:pyt    作者:python-security    | 项目源码 | 文件源码
def note_edit(request, project_id, task_id, note_id):

    proj = Project.objects.get(pk=project_id)
    task = Task.objects.get(pk=task_id)
    note = Notes.objects.get(pk=note_id)

    if request.method == 'POST':

        if task.project == proj:

            if note.task == task:

                text = request.POST.get('text', False)
                note_title = request.POST.get('note_title', False)

                note.title = note_title
                note.text = text
                note.save()

        return redirect('/taskManager/' + project_id + '/' + task_id)
    else:
        return render_to_response(
            'taskManager/note_edit.html', {'note': note}, RequestContext(request))

# A4: Insecure Direct Object Reference (IDOR)
项目:web    作者:duboviy    | 项目源码 | 文件源码
def register_page(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password1'],
                email=form.cleaned_data['email']
            )
            return HttpResponseRedirect('/')
    else:
        form = RegistrationForm()
    variables = RequestContext(request, {
        'form': form
    })
    return render_to_response(
        'registration/register.html', variables
    )
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def work_timer(
        request,
        process_id,
        commitment_id=None):
    process = get_object_or_404(Process, id=process_id)
    agent = get_agent(request)
    ct = None
    if commitment_id:
        ct = get_object_or_404(Commitment, id=commitment_id)
        #if not request.user.is_superuser:
        #    if agent != ct.from_agent:
        #        return render_to_response('valueaccounting/no_permission.html')
    template_params = create_worktimer_context(
        request,
        process,
        agent,
        ct,
    )
    return render_to_response("work/work_timer.html",
        template_params,
        context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def faircoin_history(request, resource_id):
    resource = get_object_or_404(EconomicResource, id=resource_id)
    event_list = resource.events.all()
    agent = get_agent(request)
    init = {"quantity": resource.quantity,}
    unit = resource.resource_type.unit

    paginator = Paginator(event_list, 25)

    page = request.GET.get('page')
    try:
        events = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        events = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        events = paginator.page(paginator.num_pages)

    return render_to_response("work/faircoin_history.html", {
        "resource": resource,
        "agent": agent,
        "unit": unit,
        "events": events,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def create_user(request, agent_id):
    if not request.user.is_staff:
        return render_to_response('valueaccounting/no_permission.html')
    agent = get_object_or_404(EconomicAgent, id=agent_id)
    if request.method == "POST":
        user_form = UserCreationForm(data=request.POST)
        #import pdb; pdb.set_trace()
        if user_form.is_valid():
            user = user_form.save(commit=False)
            user.email = agent.email
            is_staff = request.POST.get("is_staff")
            if is_staff == 'on':
                user.is_staff = True
            #user.last_login = datetime.datetime.now()
            user.save()
            au = AgentUser(
                agent = agent,
                user = user)
            au.save()
            if use_faircoins:
                agent.request_faircoin_address()
    return HttpResponseRedirect('/%s/%s/'
        % ('accounting/agent', agent.id))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def locations(request):
    agent = get_agent(request)
    locations = Location.objects.all()
    nolocs = Location.objects.filter(latitude=0.0)
    latitude = settings.MAP_LATITUDE
    longitude = settings.MAP_LONGITUDE
    zoom = settings.MAP_ZOOM
    return render_to_response("valueaccounting/locations.html", {
        "agent": agent,
        "locations": locations,
        "nolocs": nolocs,
        "latitude": latitude,
        "longitude": longitude,
        "zoom": zoom,
        "help": get_help("locations"),
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def radial_graph(request, agent_id):
    agent = get_object_or_404(EconomicAgent, id=agent_id)
    agents = agent.with_all_associations()
    connections = {}
    for agnt in agents:
        if agnt not in connections:
            connections[agnt] = 0
        cxs = [assn.is_associate for assn in agnt.all_has_associates()]
        for cx in cxs:
            if cx not in connections:
                connections[cx] = 0
            connections[cx] += 1

    return render_to_response("valueaccounting/radial_graph.html", {
        "agents": agents,
        "root": agent,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def exchange_types(request):
    #import pdb; pdb.set_trace()
    if request.method == "POST":
        new_form = NewExchangeTypeForm(data=request.POST)
        if new_form.is_valid():
            ext = new_form.save(commit=False)
            ext.created_by = request.user
            ext.save()

    supply_exchange_types = ExchangeType.objects.supply_exchange_types()
    demand_exchange_types = ExchangeType.objects.demand_exchange_types()
    internal_exchange_types = ExchangeType.objects.internal_exchange_types()
    new_form = NewExchangeTypeForm()

    return render_to_response("valueaccounting/exchange_types.html", {
        "supply_exchange_types": supply_exchange_types,
        "demand_exchange_types": demand_exchange_types,
        "internal_exchange_types": internal_exchange_types,
        "new_form": new_form,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def all_contributions(request):
    event_list = EconomicEvent.objects.filter(is_contribution=True)
    paginator = Paginator(event_list, 25)

    page = request.GET.get('page')
    try:
        events = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        events = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        events = paginator.page(paginator.num_pages)

    return render_to_response("valueaccounting/all_contributions.html", {
        "events": events,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def project_wip(request, project_id):
    #import pdb; pdb.set_trace()
    project = get_object_or_404(EconomicAgent, pk=project_id)
    process_list = project.wip()
    paginator = Paginator(process_list, 25)

    page = request.GET.get('page')
    try:
        processes = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        processes = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        processes = paginator.page(paginator.num_pages)

    return render_to_response("valueaccounting/project_wip.html", {
        "project": project,
        "processes": processes,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def delete_process_type_confirmation(request, 
        process_type_id, resource_type_id):
    pt = get_object_or_404(ProcessType, pk=process_type_id)
    side_effects = False
    next = request.POST.get("next")
    if next == None:
        next = '/%s/%s/' % ('accounting/edit-xbomfg', resource_type_id)
    if pt.resource_types.all():
        side_effects = True
        return render_to_response('valueaccounting/process_type_delete_confirmation.html', {
            "process_type": pt,
            "resource_type_id": resource_type_id,
            "side_effects": side_effects,
            "next": next,
            }, context_instance=RequestContext(request))
    else:
        pt.delete()
        return HttpResponseRedirect(next)
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def timeline(request, from_date, to_date, context_id):
    try:
        from_date_date = datetime.datetime(*time.strptime(from_date, '%Y_%m_%d')[0:5]).date()
        to_date_date = datetime.datetime(*time.strptime(to_date, '%Y_%m_%d')[0:5]).date()
    except ValueError:
        raise Http404
    context_id = int(context_id)
    if context_id:
        context_agent = get_object_or_404(EconomicAgent, pk=context_id)
    timeline_date = datetime.date.today().strftime("%b %e %Y 00:00:00 GMT-0600")
    unassigned = Commitment.objects.unfinished().filter(
        from_agent=None,
        event_type__relationship="work").order_by("due_date")
    return render_to_response("valueaccounting/timeline.html", {
        "orderId": 0,
        "context_id": context_id,
        "useContextId": 0,
        "from_date": from_date,
        "to_date": to_date,
        "timeline_date": timeline_date,
        "unassigned": unassigned,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def order_timeline(request, order_id):
    order = get_object_or_404(Order, pk=order_id)
    first_process = order.first_process_in_order()
    timeline_date = datetime.date.today().strftime("%b %e %Y 00:00:00 GMT-0600")
    if first_process:
        if first_process.start_date:
            timeline_date = first_process.start_date.strftime("%b %e %Y 00:00:00 GMT-0600")
    unassigned = Commitment.objects.unfinished().filter(
        independent_demand=order,
        from_agent=None,
        event_type__relationship="work").order_by("due_date")
    return render_to_response("valueaccounting/timeline.html", {
        "orderId": order.id,
        "context_id": 0,
        "useContextId": 0,
        "timeline_date": timeline_date,
        "unassigned": unassigned,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def misc(request):
    if not request.user.is_superuser:
        return render_to_response('valueaccounting/no_permission.html') 

    context_agent = None
    context_agents = EconomicAgent.objects.context_agents()
    if context_agents:
        context_agent = context_agents[0]
        for ca in context_agents:
            if ca.events.all().count() > context_agent.events.all().count():
                context_agent = ca

    ca_form = ContextAgentSelectionForm()
    if request.method == "POST":
        form = ContextAgentSelectionForm(data=request.POST)
        if form.is_valid():
            data = form.cleaned_data
            agent = data["selected_agent"]
            return HttpResponseRedirect('/%s/%s/'
                % ('accounting/create-distribution', agent.id))    

    return render_to_response("valueaccounting/misc.html", {
        "context_agent": context_agent,
        "ca_form": ca_form,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def demand(request):
    agent = get_agent(request)
    orders = Order.objects.customer_orders()
    rands = Order.objects.open_rand_orders()
    help = get_help("demand")
    nav_form = DemandExchangeNavForm(data=request.POST or None)
    if agent:
        if request.method == "POST":
            #import pdb; pdb.set_trace()
            if nav_form.is_valid():
                data = nav_form.cleaned_data
                ext = data["exchange_type"]
            return HttpResponseRedirect('/%s/%s/%s/'
                % ('accounting/exchange', ext.id, 0))

    return render_to_response("valueaccounting/demand.html", {
        "orders": orders,
        "rands": rands,
        "agent": agent,
        "nav_form": nav_form,
        "help": help,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def resource_type_lists(request):
    agent = get_agent(request)
    rt_lists = ResourceTypeList.objects.all()
    rtl_form = ResourceTypeListForm(data=request.POST or None)
    #help = get_help("demand")
    if request.method == "POST":
        if rtl_form.is_valid():
            form_data = rtl_form.cleaned_data
            rt_list = rtl_form.save()
            rt_ids = form_data["resource_types"]
            for rt_id in rt_ids:
                rt = EconomicResourceType.objects.get(id=rt_id)
                elem = ResourceTypeListElement(
                    resource_type_list=rt_list,
                    resource_type=rt)
                elem.save()
            return HttpResponseRedirect('/%s/'
                % ('accounting/resource-type-lists'))

    return render_to_response("valueaccounting/resource_type_lists.html", {
        "rt_lists": rt_lists,
        "rtl_form": rtl_form,
        "agent": agent,
        #"help": help,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def agent_stats(request, agent_id):
    agent = get_object_or_404(EconomicAgent, id=agent_id)
    scores = agent.resource_types.all()
    agents = {}
    contributions = EconomicEvent.objects.filter(is_contribution=True)
    for c in contributions:
        if c.from_agent not in agents:
            agents[c.from_agent] = Decimal("0")
        agents[c.from_agent] += c.quantity
    member_hours = []
    for key, value in agents.iteritems():
        member_hours.append((key, value))
    member_hours.sort(lambda x, y: cmp(y[1], x[1]))
    return render_to_response("valueaccounting/agent_stats.html", {
        "agent": agent,
        "scores": scores,
        "member_hours": member_hours,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def project_stats(request, context_agent_slug):
    project = None
    member_hours = []
    #import pdb; pdb.set_trace()
    if context_agent_slug:
        project = get_object_or_404(EconomicAgent, slug=context_agent_slug)
    if project:
        subs = project.with_all_sub_agents()
        ces = CachedEventSummary.objects.filter(
            event_type__relationship="work",
            context_agent__in=subs)
        if ces.count():
            agents = {}
            for ce in ces:
                agents.setdefault(ce.agent, Decimal("0"))
                agents[ce.agent] += ce.quantity
            for key, value in agents.items():
                member_hours.append((key, value))
            member_hours.sort(lambda x, y: cmp(y[1], x[1]))
    return render_to_response("valueaccounting/project_stats.html", {
        "member_hours": member_hours,
        "page_title": "All-time project stats",
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def change_event(request, event_id):
    event = get_object_or_404(EconomicEvent, pk=event_id)
    page = request.GET.get("page")
    #import pdb; pdb.set_trace()
    event_form = event.change_form(data=request.POST or None)
    if request.method == "POST":
        #import pdb; pdb.set_trace()
        page = request.POST.get("page")
        if event_form.is_valid():
            event = event_form.save(commit=False)
            event.changed_by = request.user
            event.save()
        agent = event.from_agent
        if page:
            return HttpResponseRedirect('/%s/%s/?page=%s'
                % ('accounting/contributionhistory', agent.id, page))
        else:
            return HttpResponseRedirect('/%s/%s/'
                % ('accounting/contributionhistory', agent.id))
    return render_to_response("valueaccounting/change_event.html", {
        "event_form": event_form,
        "page": page,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def labnotes_reload(
        request, 
        commitment_id, 
        was_running=0,
        was_retrying=0):
    ct = get_object_or_404(Commitment, id=commitment_id)
    #import pdb; pdb.set_trace()
    template_params = create_labnotes_context(
        request, 
        ct, 
        was_running,
        was_retrying,
    )
    return render_to_response("valueaccounting/workbook.html",
        template_params,
        context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def log_past_work(
        request, 
        commitment_id):
    ct = get_object_or_404(Commitment, id=commitment_id)
    #import pdb; pdb.set_trace()
    agent = get_agent(request)
    if not request.user.is_superuser:
        if agent != ct.from_agent:
            return render_to_response('valueaccounting/no_permission.html')
    template_params = create_past_work_context(
        request, 
        ct,
    )
    event = template_params["event"]
    if request.method == "POST":
        return HttpResponseRedirect('/%s/%s/'
            % ('accounting/labnote', ct.id))
    return render_to_response("valueaccounting/log_past_work.html",
        template_params,
        context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def todo_history(request):
    #import pdb; pdb.set_trace()
    todo_list = Commitment.objects.finished_todos().order_by('-due_date',)

    paginator = Paginator(todo_list, 25)
    page = request.GET.get('page')
    try:
        todos = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        todos = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        todos = paginator.page(paginator.num_pages)

    return render_to_response("valueaccounting/todo_history.html", {
        "todos": todos,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def labnotes(request, process_id):
    process = get_object_or_404(Process, id=process_id)
    agent = get_agent(request)
    work_commitments = process.work_requirements()
    #import pdb; pdb.set_trace()
    if work_commitments.count() == 1:
        ct = work_commitments[0]
        template_params = get_labnote_context(ct, agent)
        return render_to_response("valueaccounting/labnote.html",
            template_params,
            context_instance=RequestContext(request))
    else:
        return render_to_response("valueaccounting/labnotes.html", {
            "process": process,
            "agent": agent,
        }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def change_order(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    #import pdb; pdb.set_trace()
    order_form = OrderChangeForm(instance=order, data=request.POST or None)
    if request.method == "POST":
        next = request.POST.get("next")
        if order_form.is_valid():
            order = order_form.save()
            if next == "demand":
                return HttpResponseRedirect('/%s/'
                    % ('accounting/demand'))
            if next == "closed_work_orders":
                return HttpResponseRedirect('/%s/'
                    % ('accounting/closed-work-orders'))
    else:
        next = request.GET.get("next")

    return render_to_response("valueaccounting/change_order.html", {
        "order_form": order_form,
        "order": order,
        "next": next,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def comments(request):
    comments = Comment.objects.all().order_by("-submit_date")

    paginator = Paginator(comments, 25)
    page = request.GET.get('page')
    try:
        comment_list = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        comment_list = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        comment_list = paginator.page(paginator.num_pages)
    return render_to_response("valueaccounting/comments.html", {
        "comment_list": comment_list,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def bucket_filter_header(request):
    #import pdb; pdb.set_trace()
    header_form = FilterSetHeaderForm(data=request.POST or None)
    if request.method == "POST":
        if header_form.is_valid():
            data = header_form.cleaned_data
            agent = data["context"]
            event_type = data["event_type"]
            pattern = data["pattern"]
            if pattern:
                pattern_id = pattern.id
            else:
                pattern_id = 0
            #import pdb; pdb.set_trace()
            filter_set = data["filter_set"]
            return HttpResponseRedirect('/%s/%s/%s/%s/%s/'
                % ('accounting/bucket-filter', agent.id, event_type.id, pattern_id, filter_set))
    return render_to_response("valueaccounting/bucket_filter_header.html", {
        "header_form": header_form,
    }, context_instance=RequestContext(request))

#@login_required
项目:DCPanel    作者:vladgr    | 项目源码 | 文件源码
def copy_config(request):
    tpl = 'admin/api/custom/copy_config.html'
    servers = models.Server.objects.all()

    if request.method == 'POST':
        sfrom = int(request.POST['server_from'])
        sto = int(request.POST['server_to'])

        if sfrom == 0:
            message = 'Server "from" hasn\'t been chosen.'
            messages.error(request, message)
        elif sto == 0:
            message = 'Server "to" hasn\'t been chosen.'
            messages.error(request, message)
        elif sfrom == sto:
            message = 'Server "from" and server "to" should be different.'
            messages.error(request, message)
        else:
            count = 0
            objs = models.Conf.objects.filter(server_id=sfrom)
            for obj in objs:
                dic = {
                    'server_id': sto,
                    'filename': obj.filename,
                    'type': models.Conf.SERVER,
                    'item': obj.item
                }
                if not models.Conf.objects.filter(**dic).exists():
                    dic['data'] = obj.data
                    conf = models.Conf(**dic)
                    conf.save()
                    count += 1
            message = '{:d} configs have been copied.'.format(count)
            messages.success(request, message)

    return render_to_response(
        tpl, locals(), context_instance=RequestContext(request))
项目:NearBeach    作者:robotichead    | 项目源码 | 文件源码
def handler404(request):
    response = render_to_response(
        '404.html',
        {},
        context_instance=RequestContext(request)
    )
    response.status_code = 404
    return response
项目:NearBeach    作者:robotichead    | 项目源码 | 文件源码
def handler500(request):
    response = render_to_response(
        '500.html',
        {},
        context_instance=RequestContext(request)
    )
    response.status_code = 500
    return response
项目:Cypher    作者:NullArray    | 项目源码 | 文件源码
def login_user(request):
    logout(request)
    username = password = ''
    if request.POST:
        username = request.POST['username']
        password = request.POST['password']

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(main)
    return render_to_response('login.html', (request))
项目:Cypher    作者:NullArray    | 项目源码 | 文件源码
def main(request):
    return render_to_response('main.html', (request))