Python django.template 模块,RequestContext() 实例源码

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

项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def wizard(request):
    form = FilterWizard([FilterWiZardForm1, FilterWiZardForm2, FilterWiZardForm3])
    if request.method == 'GET':
        print('CHECK HERE')
        query_string = request.META['QUERY_STRING']
        if query_string != '':
            print("LIMPANDO")
            new_query_string = []
            query_string = query_string.split('&')
            for item in query_string:
                if not (item.startswith('csrfmiddlewaretoken') or item.startswith('hash') or item.startswith('wizard')):
                    #get here only the ones need to be cleaned Ex. 1-chr
                    item = "-".join(item.split('-', 2)[1:])
                    new_query_string.append(item)

            #create new query
            filterstring = "&".join(new_query_string)
            # return HttpResponseRedirect('/filter_analysis/?%s' % (filterstring))
            return redirect(reverse('filter_analysis')+'?'+filterstring)





    return form(context=RequestContext(request), request=request)
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def wizard(request):
    form = FilterWizard([FilterWiZardForm1, FilterWiZardForm2, FilterWiZardForm3])
    if request.method == 'GET':
        print('CHECK HERE')
        query_string = request.META['QUERY_STRING']
        if query_string != '':
            print("LIMPANDO")
            new_query_string = []
            query_string = query_string.split('&')
            for item in query_string:
                if not (item.startswith('csrfmiddlewaretoken') or item.startswith('hash') or item.startswith('wizard')):
                    #get here only the ones need to be cleaned Ex. 1-chr
                    item = "-".join(item.split('-', 2)[1:])
                    new_query_string.append(item)

            #create new query
            filterstring = "&".join(new_query_string)
            # return HttpResponseRedirect('/filter_analysis/?%s' % (filterstring))
            return redirect(reverse('filter_analysis')+'?'+filterstring)





    return form(context=RequestContext(request), request=request)
项目: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))
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def render_table_actions(self):
        """Renders the actions specified in ``Meta.table_actions``."""
        template_path = self._meta.table_actions_template
        table_actions_template = template.loader.get_template(template_path)
        bound_actions = self.get_table_actions()
        extra_context = {"table_actions": bound_actions,
                         "table_actions_buttons": [],
                         "table_actions_menu": []}
        if self._meta.filter and (
                self._filter_action(self._meta._filter_action, self.request)):
            extra_context["filter"] = self._meta._filter_action
        for action in bound_actions:
            if action.__class__ in self._meta.table_actions_menu:
                extra_context['table_actions_menu'].append(action)
            elif action != extra_context.get('filter'):
                extra_context['table_actions_buttons'].append(action)
        context = template.RequestContext(self.request, extra_context)
        self.set_multiselect_column_visibility(len(bound_actions) > 0)
        return table_actions_template.render(context)
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def render_row_actions(self, datum, pull_right=True, row=False):
        """Renders the actions specified in ``Meta.row_actions`` using the
        current row data. If `row` is True, the actions are rendered in a row
        of buttons. Otherwise they are rendered in a dropdown box.
        """
        if row:
            template_path = self._meta.row_actions_row_template
        else:
            template_path = self._meta.row_actions_dropdown_template

        row_actions_template = template.loader.get_template(template_path)
        bound_actions = self.get_row_actions(datum)
        extra_context = {"row_actions": bound_actions,
                         "row_id": self.get_object_id(datum),
                         "pull_right": pull_right}
        context = template.RequestContext(self.request, extra_context)
        return row_actions_template.render(context)
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def __init__(self, request, template, context, content_type, **kwargs):
        super(BaseCsvResponse, self).__init__()
        self['Content-Disposition'] = 'attachment; filename="%s"' % (
            kwargs.get("filename", "export.csv"),)
        self['Content-Type'] = content_type
        self.context = context
        self.header = None
        if template:
            # Display some header info if provided as a template
            header_template = django_template.loader.get_template(template)
            context = django_template.RequestContext(request, self.context)
            self.header = header_template.render(context)

        if self.header:
            self.out.write(self.encode(self.header))

        self.write_csv_header()

        for row in self.get_row_data():
            self.write_csv_row(row)

        self.out.flush()
        self.content = self.out.getvalue()
        self.out.close()
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def __init__(self, request, template, context, content_type, **kwargs):
        super(BaseCsvStreamingResponse, self).__init__()
        self['Content-Disposition'] = 'attachment; filename="%s"' % (
            kwargs.get("filename", "export.csv"),)
        self['Content-Type'] = content_type
        self.context = context
        self.header = None
        if template:
            # Display some header info if provided as a template
            header_template = django_template.loader.get_template(template)
            context = django_template.RequestContext(request, self.context)
            self.header = header_template.render(context)

        self._closable_objects.append(self.out)

        self.streaming_content = self.get_content()
项目: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))
项目: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),
        )
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def test_preferences_cp(self):
        request = RequestFactory().get('/')
        context = context_processors.preferences_cp(request)

        # context should have preferences.
        my_preferences = context['preferences']

        # preferences should have test MyPreferences object member.
        my_preferences = my_preferences.MyPreferences
        self.failUnless(isinstance(my_preferences, MyPreferences),
                        "%s should be instance of MyPreferences." % my_preferences)

        # With preferences_cp is loaded as a TEMPLATE_CONTEXT_PROCESSORS
        # templates should have access to preferences object.
        context_instance = RequestContext(request)
        t = Template("{% if preferences %}{{ preferences }}{% endif %}")
        self.failUnless(t.render(context_instance), "preferences should be \
available in template context.")

        t = Template("{% if preferences.MyPreferences %}{{ \
preferences.MyPreferences }}{% endif %}")
        self.failUnless(t.render(context_instance), "MyPreferences should be \
available as part of preferences var in template context.")
项目: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 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_create(request, project_id, task_id):
    if request.method == 'POST':

        parent_task = Task.objects.get(pk=task_id)

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

        note = Notes(
            title=note_title,
            text=text,
            user=request.user,
            task=parent_task)

        note.save()
        return redirect('/taskManager/' + project_id + '/' +
                        task_id, {'new_note_added': True})
    else:
        return render_to_response(
            'taskManager/note_create.html', {'task_id': task_id}, 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 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 test_patterns(request):
    pattern_form = PatternSelectionForm(data=request.POST or None)
    pattern = None
    slots = []
    if request.method == "POST":
        if pattern_form.is_valid():
            pattern = pattern_form.cleaned_data["pattern"]
            slots = pattern.event_types()
            #import pdb; pdb.set_trace()
            for slot in slots:
                slot.resource_types = pattern.get_resource_types(slot)
                slot.facets = pattern.facets_for_event_type(slot)

    return render_to_response("valueaccounting/test_patterns.html", {
        "pattern_form": pattern_form,
        "pattern": pattern,
        "slots": slots,
    }, 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 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 finished_processes(request, agent_id):
    #import pdb; pdb.set_trace()
    project = get_object_or_404(EconomicAgent, pk=agent_id)
    process_list = project.finished_processes()
    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/finished_processes.html", {
        "project": project,
        "processes": processes,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def edit_extended_bill(request, resource_type_id):

    #start_time = time.time()
    rt = get_object_or_404(EconomicResourceType, pk=resource_type_id)
    output_ctype, inheritance = rt.main_producing_process_type_relationship()
    #import pdb; pdb.set_trace()
    nodes = rt.generate_xbill()
    resource_type_form = EconomicResourceTypeChangeForm(instance=rt)
    feature_form = FeatureForm()
    names = EconomicResourceType.objects.values_list('name', flat=True)
    resource_names = '~'.join(names)
    #end_time = time.time()
    #print("edit_extended_bill view elapsed time was %g seconds" % (end_time - start_time))
    return render_to_response("valueaccounting/edit_xbill.html", {
        "resource_type": rt,
        "output_ctype": output_ctype,
        "nodes": nodes,
        "photo_size": (128, 128),
        "big_photo_size": (200, 200),
        "resource_type_form": resource_type_form,
        "feature_form": feature_form,
        "resource_names": resource_names,
        "help": get_help("ed_asmbly_recipe"),
    }, 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 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 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 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 work_now(
        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_worknow_context(
        request, 
        process,
        agent,
        ct, 
    )
    return render_to_response("valueaccounting/work_now.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 open_todos(request):
    #import pdb; pdb.set_trace()
    todo_list = Commitment.objects.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/open_todos.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 resource_facet_table(request):
    headings = ["Resource Type"]
    rows = []
    facets = Facet.objects.all()
    for facet in facets:
        headings.append(facet)
    for rt in EconomicResourceType.objects.all():
        row = [rt, ]
        for i in range(0, facets.count()):
            row.append("")
        for rf in rt.facets.all():
            cell = headings.index(rf.facet_value.facet)
            row[cell] = rf
        rows.append(row)     
    return render_to_response("valueaccounting/resource_facets.html", {
        "headings": headings,
        "rows": rows,
    }, 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 inventory_board_demo(request):
    #import pdb; pdb.set_trace()
    pattern = ProcessPattern.objects.get(name="Change")
    resource_form = ResourceFlowForm(pattern=pattern)
    process_form = PlanProcessForm()
    move_harvester_form = ExchangeFlowForm()
    move_dryer_form = ExchangeFlowForm()
    move_seller_form = ExchangeFlowForm()

    return render_to_response("valueaccounting/inventory_board_demo.html", {
        "resource_form": resource_form,
        "process_form": process_form,
        "move_harvester_form": move_harvester_form,
        "move_dryer_form": move_dryer_form,
        "move_seller_form": move_seller_form,
    }, 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
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def skill_suggestions(request):
    state = "new"
    state_form = RequestStateForm(
        initial={"state": "new",},
        data=request.POST or None)
    #import pdb; pdb.set_trace()
    if request.method == "POST":
        if state_form.is_valid():
            data = state_form.cleaned_data
            state = data["state"]
    suggestions =  SkillSuggestion.objects.filter(state=state)

    return render_to_response("valueaccounting/skill_suggestions.html", {
        "help": get_help("skill_suggestions"),
        "suggestions": suggestions,
        "state_form": state_form,
        "state": state,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def membership_requests(request):
    state = "new"
    state_form = RequestStateForm(
        initial={"state": "new",},
        data=request.POST or None)
    #agent_form = MembershipAgentSelectionForm()
    #import pdb; pdb.set_trace()
    if request.method == "POST":
        if state_form.is_valid():
            data = state_form.cleaned_data
            state = data["state"]
    requests =  MembershipRequest.objects.filter(state=state)

    return render_to_response("valueaccounting/membership_requests.html", {
        "help": get_help("membership_requests"),
        "requests": requests,
        "state_form": state_form,
        "state": state,
        #"agent_form": agent_form,
    }, context_instance=RequestContext(request))
项目:weibo-spider    作者:bowenpay    | 项目源码 | 文件源码
def weibo_list(request):
    context = {}
    # ????
    params = request.GET.copy()
    _obj_list = Weibo.objects.order_by('-id')

    paginator = Paginator(_obj_list, 50 )  # Show 10 contacts per page

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

    context.update({
        "active_nav": "weibos.weibo",
        "weibos": _objs,
        "params": params
    })
    return render_to_response('weibos/weibo_list.html', {}, context_instance=RequestContext(request, context))
项目:modeltranslation    作者:intelligenia    | 项目源码 | 文件源码
def export_translations(request, language):
    """
    Vista de exportación de las traducciones
    """
    FieldTranslation.delete_orphan_translations()
    translations = FieldTranslation.objects.filter(lang=language)
    for trans in translations:
        trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"")
        trans.translation = trans.translation.replace("'","\'").replace("\"","\\\"")
    replacements = {"translations":translations, "lang":language}
    if len(settings.ADMINS)>0:
        replacements["last_translator"] = settings.ADMINS[0][0]
        replacements["last_translator_email"] = settings.ADMINS[0][1]
    if settings.WEBSITE_NAME:
        replacements["website_name"] = settings.WEBSITE_NAME
    response = render(request=request, template_name='modeltranslation/admin/export_translations.po', dictionary=replacements, context_instance=RequestContext(request), content_type="text/x-gettext-translation")
    response['Content-Disposition'] = 'attachment; filename="{0}.po"'.format(language)
    return response


########################################################################
########################################################################
## Actualizar las traducciones
项目:modeltranslation    作者:intelligenia    | 项目源码 | 文件源码
def export_translations(request, language):
    """
    Export translations view.
    """
    FieldTranslation.delete_orphan_translations()
    translations = FieldTranslation.objects.filter(lang=language)
    for trans in translations:
        trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"")
        trans.translation = trans.translation.replace("'","\'").replace("\"","\\\"")
    replacements = {"translations":translations, "lang":language}
    if len(settings.ADMINS)>0:
        replacements["last_translator"] = settings.ADMINS[0][0]
        replacements["last_translator_email"] = settings.ADMINS[0][1]
    if settings.WEBSITE_NAME:
        replacements["website_name"] = settings.WEBSITE_NAME
    response = render(request=request, template_name='modeltranslation/admin/export_translations.po', dictionary=replacements, context_instance=RequestContext(request), content_type="text/x-gettext-translation")
    response['Content-Disposition'] = 'attachment; filename="{0}.po"'.format(language)
    return response


########################################################################
########################################################################
## Update translations
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def template_render(template, context=None, request=None):
    """
    Passing Context or RequestContext to Template.render is deprecated in 1.9+,
    see https://github.com/django/django/pull/3883 and
    https://github.com/django/django/blob/1.9/django/template/backends/django.py#L82-L84

    :param template: Template instance
    :param context: dict
    :param request: Request instance
    :return: rendered template as SafeText instance
    """
    if isinstance(template, Template):
        if request:
            context = RequestContext(request, context)
        else:
            context = Context(context)
        return template.render(context)
    # backends template, e.g. django.template.backends.django.Template
    else:
        return template.render(context, request=request)