Python django.template.RequestContext() Examples

The following are 30 code examples for showing how to use django.template.RequestContext(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.template , or try the search function .

Example 1
Project: crowdata   Author: crowdata   File: views.py    License: MIT License 6 votes vote down vote up
def form_detail(request, slug, template="forms/form_detail.html"):
    form = get_object_or_404(models.DocumentSetForm, slug=slug)
    request_context = RequestContext(request)
    args = (form, request_context, request.POST or None)

    form_for_form = forms.DocumentSetFormForForm(*args)

    if request.method == 'POST':
        if not form_for_form.is_valid():
            form_invalid.send(sender=request, form=form_for_form)
            return HttpResponseBadRequest(json.dumps(form_for_form.errors), content_type='application/json')
        else:
            entry = form_for_form.save()
            form_valid.send(sender=request, form=form_for_form, entry=entry, document_id=request.session['document_id_for_entry'])
            return HttpResponse('')
    return render_to_response(template, { 'form': form }, request_context) 
Example 2
Project: crowdata   Author: crowdata   File: views.py    License: MIT License 6 votes vote down vote up
def choose_current_organization(request):
    """ Show which Organizations can be selected """
    organizations = request.user.organization_set.all()
    
    current_organization = None
    
    try:
        user_profile = request.user.get_profile()      
    except models.UserProfile.DoesNotExist:
        user_profile = models.UserProfile(user=request.user, name=request.user.get_full_name())
        user_profile.save()
        
    if user_profile:
        current_organization = user_profile.current_organization

    template = 'choose_current_organization.html' if organizations.count() > 0 else 'without_organization.html'
    return render_to_response(template, {
                                'organizations': organizations, 
                                'current_organization': current_organization,
                                'organization_signup_link': settings.ORGANIZATION_SIGNUP_LINK
                               },
                               context_instance = RequestContext(request)) 
Example 3
Project: coursys   Author: sfu-fas   File: view_capabilities.py    License: GNU General Public License v3.0 6 votes vote down vote up
def view_capabilities(request):
    instructors = Person.objects.filter(role__role__in=["FAC", "SESS", "COOP"],
                                        role__unit__in=request.units)
    capabilities = []
    for i in instructors:
        capabilities.append(TeachingCapability.objects.filter(instructor=i))
    capabilities_list = list(zip(instructors, capabilities))

    courses = PlanningCourse.objects.filter(owner__in=request.units)
    capabilities = []
    for c in courses:
        capabilities.append(TeachingCapability.objects.filter(course=c))
    course_capabilities_list = list(zip(courses, capabilities))

    return render(request, "planning/view_capabilities.html",
                              {'capabilities_list': capabilities_list,
                               'course_capabilities_list': course_capabilities_list},
                              context_instance=RequestContext(request)) 
Example 4
Project: mendelmd   Author: raonyguimaraes   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example 5
Project: mendelmd   Author: raonyguimaraes   File: family_analysis.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example 6
Project: mendelmd   Author: raonyguimaraes   File: family_analysis.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example 7
Project: mendelmd   Author: raonyguimaraes   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)) 
Example 8
Project: mendelmd   Author: raonyguimaraes   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)) 
Example 9
Project: mendelmd   Author: raonyguimaraes   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example 10
Project: mendelmd   Author: raonyguimaraes   File: family_analysis.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example 11
Project: mendelmd   Author: raonyguimaraes   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)) 
Example 12
Project: GTDWeb   Author: lanbing510   File: response.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _resolve_context(self, context):
        # This wrapper deprecates returning a Context or a RequestContext in
        # subclasses that override resolve_context. It can be removed in
        # Django 1.10. If returning a Context or a RequestContext works by
        # accident, it won't be an issue per se, but it won't be officially
        # supported either.
        new_context = self.resolve_context(context)
        if isinstance(new_context, RequestContext) and self._request is None:
            self._request = new_context.request
        if isinstance(new_context, Context):
            warnings.warn(
                "{}.resolve_context() must return a dict, not a {}.".format(
                    self.__class__.__name__, new_context.__class__.__name__),
                RemovedInDjango110Warning, stacklevel=2)
            # It would be tempting to do new_context = new_context.flatten()
            # here but that would cause template context processors to run for
            # TemplateResponse(request, template, Context({})), which would be
            # backwards-incompatible. As a consequence another deprecation
            # warning will be raised when rendering the template. There isn't
            # much we can do about that.
        return new_context 
Example 13
Project: aumfor   Author: virtualrealitysystems   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def index(request):
    offline_register(request)

    if request.user.is_authenticated():
        request.session['username'] = request.user.username
        request.session['uid'] = request.user.pk
    else:
        request.session['uid'] = -1

    print(">>>>>>>", request.session.get('newdump'));
    # if request.session.get('newdump'):
    #      dumpid = request.session.get('newdump')
    #  return render(request,'index.html',context={"dump":dumpid})
    return render_to_response("index.html", locals(), context_instance=RequestContext(request))
    # contex = {
    #     "request":RequestContext(request),
    #     "dump":dumpid
    # }
    # return render(request,'index.html',contex) 
Example 14
Project: aumfor   Author: virtualrealitysystems   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def process_detail(request):
    context = {}
    try:
        if request.POST.get("setPid") and request.POST.get("setDumpid"):

            context = {
                "pid": request.POST.get("setPid"),
                "dumpid": request.POST.get("setDumpid"),
                "dumpname": request.POST.get("dumpName")
            }
        else:
            raise Exception("No Process Id or Dump Id Specified")

    except Exception as ex:
        raise Exception(ex)
    return render_to_response("singleprocess.html", context, context_instance=RequestContext(request)) 
Example 15
Project: DCRM   Author: 82Flex   File: test_all.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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.") 
Example 16
Project: qmpy   Author: wolverton-research-group   File: calculation.py    License: MIT License 6 votes vote down vote up
def calculation_view(request, calculation_id):
    calculation = Calculation.objects.get(pk=calculation_id)
    data = get_globals()
    data['calculation'] = calculation
    data['stdout'] = ''
    data['stderr'] = ''

    if os.path.exists(os.path.join(calculation.path, 'stdout.txt')):
        with open(os.path.join(calculation.path, 'stdout.txt')) as fr:
            data['stdout'] = fr.read()
    if os.path.exists(os.path.join(calculation.path, 'stderr.txt')):
        with open(os.path.join(calculation.path, 'stderr.txt')) as fr:
            data['stderr'] = fr.read()
    try:
        data['incar'] = ''.join(calculation.read_incar())
    except VaspError:
        data['incar'] = 'Could not read INCAR'

    if not calculation.dos is None:
        script, div = components(calculation.dos.bokeh_plot)
        data['dos'] = script
        data['dosdiv'] = div

    return render_to_response('analysis/calculation.html',
            data, RequestContext(request)) 
Example 17
Project: fomalhaut-panel   Author: restran   File: views.py    License: MIT License 6 votes vote down vote up
def create_admin(request):
    """
    网站刚开始运行时,没有管理员,需要创建一个
    :param request:
    :return:
    """
    if SiteUser.has_admin():
        return error_404(request)
    else:
        request.page_title = '创建管理员'
        return render_to_response('accounts/create_admin.html', {'request': request})
        # 使用 context_instance=RequestContext(request) 会出现问题
        # Model class django.contrib.auth.models. Permission doesn't declare an explicit app_label and either
        # isn't in an application in INSTALLED_APPS or else was imported before its application was loaded.
        # return render_to_response('accounts/create_admin.html', {'request': request},
        #                            context_instance=RequestContext(request))
        # 解决csrf_protect不能工作,在前端不能显示csrf_token
        # 加上context_instance=RequestContext(request) 
Example 18
Project: pyt   Author: python-security   File: views.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 19
Project: pyt   Author: python-security   File: views.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 20
Project: rdmo   Author: rdmorganiser   File: test_tags.py    License: Apache License 2.0 6 votes vote down vote up
def test_i18n_switcher(rf):
    """ The language switcher is rendered correctly. """

    # create a fake template with a name
    template = "{% load core_tags %}{% i18n_switcher %}"

    # set a language
    translation.activate(settings.LANGUAGES[0][0])

    # render the link
    request = rf.get(reverse('home'))
    context = RequestContext(request, {})
    rendered_template = Template(template).render(context)
    for language in settings.LANGUAGES:
        if language == settings.LANGUAGES[0]:
            assert '<a href="/i18n/%s/"><u>%s</u></a>' % language in rendered_template
        else:
            assert'<a href="/i18n/%s/">%s</a>' % language in rendered_template 
Example 21
Project: MPContribs   Author: materialsproject   File: views.py    License: MIT License 5 votes vote down vote up
def get_context(request):
    ctx = RequestContext(request)
    ctx["API_CNAME"] = os.environ["API_CNAME"]
    ctx["API_PORT"] = os.environ["API_PORT"]
    ctx["TRADEMARK"] = os.environ.get("TRADEMARK", "")
    return ctx 
Example 22
Project: gazetteer   Author: LibraryOfCongress   File: views.py    License: MIT License 5 votes vote down vote up
def search(request):
    d = RequestContext(request, {})
    return render_to_response("search.html", d) 
Example 23
Project: gazetteer   Author: LibraryOfCongress   File: views.py    License: MIT License 5 votes vote down vote up
def feature_detail(request, id):
    feature = get_object_or_404(Feature, pk=id)
    geojson = json.dumps(feature.get_geojson())
    d = RequestContext(request, {
        'feature': feature,
        'geojson': geojson
    })
    return render_to_response("feature.html", d) 
Example 24
Project: gazetteer   Author: LibraryOfCongress   File: views.py    License: MIT License 5 votes vote down vote up
def index(request):
    places_count = Place.objects.count("*")
    context = RequestContext(request, {
        'total_count': places_count
    })
    return render_to_response("index.html", context) 
Example 25
Project: gazetteer   Author: LibraryOfCongress   File: views.py    License: MIT License 5 votes vote down vote up
def edit_place(request, place_id):
    place = get_place_or_404(place_id)
    geojson = json.dumps(place.to_geojson())
    context = RequestContext(request, {
        'place': place,
        'place_geojson': geojson
    })
    return render_to_response("edit_place.html", context) 
Example 26
Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_retrieve_get_param(self):
        out = Template(
            "{% load url_tags %}"
            "{% get_parameters %}"
        ).render(RequestContext(self.request, {}))
        self.assertTrue(out == "page=3&sort=asc" or out == "sort=asc&page=3") 
Example 27
Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_except_fields(self):
        out = Template(
            "{% load url_tags %}"
            "{% get_parameters 'sort' %}"
        ).render(RequestContext(self.request, {}))
        self.assertEqual(out, "page=3") 
Example 28
Project: yang-explorer   Author: CiscoDevNet   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def module_handler(request):
    """
    Handle module request from UI. Response from this request builds
    UI Explorer tree
    """
    logger.debug("module_handler: enter")
    lst = []
    if request.user.is_authenticated():
        path = request.GET.get('node', '')
        deep = request.GET.get('deep', '')
        username = request.user.username
        if path == 'root':
            # Request for root models
            modules = ModuleAdmin.get_modulelist(username)
            modules.sort()
            for m in modules:
                lst.append(node_t.format(m.split('@')[0]))
        else:
            modules = [path.split('/')[0]]
            for module in modules:
                filename = ModuleAdmin.cxml_path(username, module)
                if filename is not None:
                    logger.debug("module_handler: loading " + filename)
                    module = cxml.get_cxml(filename)
                    nodes = module.get_lazy_subtree(path, deep)
                    lst.extend([ET.tostring(node) for node in annotate(nodes)])
                else:
                    logger.error("module_handler: %s not found !!" + module)

    logger.debug("module_handler: exit")
    return render_to_response('loader.xml', {'nodes': lst}, RequestContext(request)) 
Example 29
Project: yang-explorer   Author: CiscoDevNet   File: security.py    License: Apache License 2.0 5 votes vote down vote up
def policy_handler(request):
    return render_to_response('crossdomain.xml', {}, RequestContext(request)) 
Example 30
Project: crowdata   Author: crowdata   File: views.py    License: MIT License 5 votes vote down vote up
def transcription_new(request, document_set):
    doc_set = get_object_or_404(models.DocumentSet, slug=document_set)

    document = None
    if request.GET.get('document_id') is not None and request.user.is_staff:
        document = get_object_or_404(models.Document, pk=request.GET.get('document_id'),
                                     document_set=doc_set)
    else:
        candidates = doc_set.get_pending_documents().exclude(form_entries__user=request.user)

        if candidates.count() == 0:
            # TODO Redirect to a message page: "you've gone through all the documents in this project!"
            return render_to_response('no_more_documents.html',
                                      { 'document_set': doc_set },
                                      context_instance=RequestContext(request))

        document = candidates.order_by('?')[0]

    # save the candidate document in the session, for later use
    # in signals.create_entry
    request.session['document_id_for_entry'] = document.id

    return render(request,
                  'transcription_new.html',
                  {
                      'document': document,
                      'head_html': document.document_set.head_html,
                      'pending_documents_count': doc_set.get_pending_documents_count_for_user(request.user),
                      'verified_documents_count': doc_set.get_verified_documents_count_for_user(request.user),
                      'reviewed_documents_count': doc_set.get_reviewed_documents_count_for_user(request.user)
                  })