Python django.shortcuts.render_to_response() Examples

The following are 30 code examples for showing how to use django.shortcuts.render_to_response(). 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.shortcuts , 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: django-usersettings2   Author: mishbahr   File: admin.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render_select_site_form(self, request, context, form_url=''):
        """
        Render the site choice form.
        """
        app_label = self.opts.app_label
        context.update({
            'has_change_permission': self.has_change_permission(request),
            'form_url': mark_safe(form_url),
            'opts': self.opts,
            'add': True,
            'save_on_top': self.save_on_top,
        })

        return render_to_response(self.select_site_form_template or [
            'admin/%s/%s/select_site_form.html' % (app_label, self.opts.object_name.lower()),
            'admin/%s/select_site_form.html' % app_label,
            'admin/usersettings/select_site_form.html',  # added default here
            'admin/select_site_form.html'
        ], context) 
Example 4
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 5
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 6
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 7
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 8
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 9
Project: lykops   Author: lykops   File: options.py    License: Apache License 2.0 6 votes vote down vote up
def detail(self, request):
        
        '''
        查看用户的ansible的option数据
        '''
        
        result = self._is_login(request)
        if result[0] :
            username = result[1]
        else :
            return HttpResponseRedirect(reverse('login'))
    
        vault_password = request.session['vault_password']
        result = self.ansible_option_api.detail(username, vault_password)
        if result[0] :
            data = result[1]
            error_message = ''
            self.logger.info(self.username + ' 查看用户' + username + '的ansible配置成功')
        else :
            data = {}
            error_message = self.username + ' 查看用户' + username + '的ansible配置失败,查询时发生错误,原因:' + result[1]
            self.logger.error(error_message) 
            error_message = result[1]
            
        return render_to_response('option_detail.html', {'data':data, 'login_user':username, 'error_message':error_message, 'nav_html':self.nav_html, 'lately_whereabouts':self.latelywhere_html}) 
Example 10
Project: qmpy   Author: wolverton-research-group   File: composition.py    License: MIT License 6 votes vote down vote up
def generic_composition_view(request, search=None):
    data = {'search':search}
    composition = ''
    space = []
    if request.method == 'POST':
        p = request.POST
        search = p.get('search', '')
        data.update(p)
    if not search:
        return render_to_response('materials/generic_composition.html',
                data,
                RequestContext(request))
        
    gc = GenericComposition(search)
    data['gc'] = gc
    return render_to_response('materials/generic_composition.html', 
            data,
            RequestContext(request)) 
Example 11
Project: qmpy   Author: wolverton-research-group   File: references.py    License: MIT License 6 votes vote down vote up
def journal_view(request, journal_id):
    journal = Journal.objects.get(id=journal_id)
    dates = journal.references.values_list('year', flat=True)
    plt.hist(dates)
    plt.xlabel('Year')
    plt.ylabel('# of publications with new materials')
    img = StringIO.StringIO()
    plt.savefig(img, dpi=75, bbox_inches='tight')
    data_uri = 'data:image/jpg;base64,'
    data_uri += img.getvalue().encode('base64').replace('\n', '')
    plt.close()

    some_entries = Entry.objects.filter(reference__journal=journal)[:20]
    data = get_globals()
    data.update({'journal':journal, 
        'hist':data_uri,
        'entries':some_entries})
    return render_to_response('data/reference/journal.html', 
            data,
            RequestContext(request)) 
Example 12
Project: qmpy   Author: wolverton-research-group   File: references.py    License: MIT License 6 votes vote down vote up
def author_view(request, author_id):
    author = Author.objects.get(id=author_id)
    materials = Entry.objects.filter(reference__author_set=author)
    coauths = {}
    for co in Author.objects.filter(references__author_set=author):
        papers = Reference.objects.filter(author_set=author)
        papers = papers.filter(author_set=co)
        mats = Entry.objects.filter(reference__in=papers)
        data = {'papers': papers.distinct().count(),
                'materials': mats.distinct().count()}
        coauths[co] = data

    data = get_globals()
    data.update({'author':author,
        'materials':materials,
        'coauthors':coauths})
    return render_to_response('data/reference/author.html', 
            data,
            RequestContext(request)) 
Example 13
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 14
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 15
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 16
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 17
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 18
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 19
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)
                  }) 
Example 20
Project: crowdata   Author: crowdata   File: admin.py    License: MIT License 5 votes vote down vote up
def cluster_canons(self, request):

      if request.GET.get('ids') is None:

        the_canon_id = int(request.POST['canon'])
        the_canon = models.CanonicalFieldEntryLabel.objects.get(pk=the_canon_id)

        canon_ids = [int(i) for i in request.POST['ids'].split(',')]
        canon_ids.remove(the_canon_id)

        canons_to_cluster = models.CanonicalFieldEntryLabel.objects.filter(id__in=canon_ids)

        # Asign all entries to the canon
        # Remove the empty canons
        for canon in canons_to_cluster:
          canon.reassign_entries_to(the_canon)
          if not canon.has_entries():
            canon.delete()

        # cluster the canons
        return redirect(reverse('admin:crowdataapp_canonicalfieldentrylabel_changelist'))
      else:
        canon_ids = [int(i) for i in request.GET['ids'].split(',')]
        canons_to_cluster = models.CanonicalFieldEntryLabel.objects.filter(id__in=canon_ids)

        # Check that all the canons to cluster have the same form-field
        canons_with_the_same_form_field = canons_to_cluster.filter(form_field=canons_to_cluster[0].form_field)
        if (len(canons_with_the_same_form_field) == len(canons_to_cluster)):
          return render_to_response('admin/cluster_canons.html',
                                 {
                                  'canon_ids': request.GET['ids'],
                                  'canons': canons_to_cluster,
                                  'current_app': self.admin_site.name
                                 },
                                 RequestContext(request))
        else:
          return redirect(reverse('admin:crowdataapp_canonicalfieldentrylabel_changelist')) 
Example 21
Project: crowdata   Author: crowdata   File: admin.py    License: MIT License 5 votes vote down vote up
def add_documents_view(self, request, document_set_id):
        """ add a bunch of documents to
         a DocumentSet by uploading a CSV """
        document_set = get_object_or_404(self.model, pk=document_set_id)
        if request.FILES.get('csv_file'):
            # got a CSV, process, check and create
            csvreader = csv.reader(request.FILES.get('csv_file'))

            header_row = csvreader.next()
            if [h.strip() for h in header_row] != ['document_title', 'document_url']:
                messages.error(request,
                               _('Header cells must be document_title and document_url'))


            count = 0
            try:
                with transaction.commit_on_success():
                    for row in csvreader:
                        document_set.documents.create(name=row[0].strip(),
                                                      url=row[1].strip())
                        count += 1
            except:
                messages.error(request,
                               _('Could not create documents'))

                return redirect(reverse('admin:document_set_add_documents',
                                        args=(document_set_id,)))

            messages.info(request,
                          _('Successfully created %(count)d documents') % { 'count': count })

            return redirect(reverse('admin:crowdataapp_documentset_changelist'))

        else:
            return render_to_response('admin/document_set_add_documents.html',
                                      {
                                          'document_set': document_set,
                                          'current_app': self.admin_site.name,
                                      },
                                      RequestContext(request)) 
Example 22
Project: StormOnline   Author: stormsha   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def page_not_found(request):
    from django.shortcuts import render_to_response
    response = render_to_response('404.html', {})
    response.status_code = 404
    return response


# ----------全局404处理函数--------------------- 
Example 23
Project: StormOnline   Author: stormsha   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def page_error(request):
    from django.shortcuts import render_to_response
    response = render_to_response('500.html', {})
    response.status_code = 500
    return response 
Example 24
Project: browserscope   Author: elsigh   File: handlers.py    License: Apache License 2.0 5 votes vote down vote up
def RunRichText2Tests(request):
  params = {
    'classes': common.CLASSES,
    'commonIDPrefix': common.TEST_ID_PREFIX,
    'strict': False,
    'suites': [
      SELECTION_TESTS,
      APPLY_TESTS,
      APPLY_TESTS_CSS,
      CHANGE_TESTS,
      CHANGE_TESTS_CSS,
      UNAPPLY_TESTS,
      UNAPPLY_TESTS_CSS,
      DELETE_TESTS,
      FORWARDDELETE_TESTS,
      INSERT_TESTS,

      QUERYSUPPORTED_TESTS,
      QUERYENABLED_TESTS,
      QUERYINDETERM_TESTS,
      QUERYSTATE_TESTS,
      QUERYSTATE_TESTS_CSS,
      QUERYVALUE_TESTS,
      QUERYVALUE_TESTS_CSS
    ]
  }
  return shortcuts.render_to_response('%s/templates/richtext2.html' % common.CATEGORY, params) 
Example 25
Project: browserscope   Author: elsigh   File: handlers.py    License: Apache License 2.0 5 votes vote down vote up
def EditableIframe(request):

  params = {}
  return shortcuts.render_to_response('richtext/templates/editable.html', params) 
Example 26
Project: mendelmd   Author: raonyguimaraes   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def view(request, pathway_id):
    print(pathway_id)
    
#    pathway_data = kegg_rest_request('get/hsa%s' % (pathway_id))
    pathway = Pathway.objects.get(kegg=pathway_id)

     
    pathway.genes = pathway.genes.split(',')
    print(pathway.genes)
    
#    genes = parse_genes(pathway_data)
#    pathway = {}
#    pathway['name'] = pathway_data.split('\n')[1].replace('NAME', '') 
#    #get gene_ids
#    genelist = []
#    for gene in genes:
#        
#        genelist.append('hsa:%s' % gene['id'])
##        print gene['id']
#    gene_url = '+'.join(genelist)
#    url = '/conv/ncbi-geneid/%s' % (gene_url)
#    results = kegg_rest_request(url)
    #print results
    
    
    #if request.method == 'GET':
    return render_to_response('pathway_analysis/view.html', {'pathway':pathway}, context_instance=RequestContext(request)) 
Example 27
Project: mendelmd   Author: raonyguimaraes   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def view(request, pathway_id):
    print(pathway_id)
    
#    pathway_data = kegg_rest_request('get/hsa%s' % (pathway_id))
    pathway = Pathway.objects.get(kegg=pathway_id)

     
    pathway.genes = pathway.genes.split(',')
    print(pathway.genes)
    
#    genes = parse_genes(pathway_data)
#    pathway = {}
#    pathway['name'] = pathway_data.split('\n')[1].replace('NAME', '') 
#    #get gene_ids
#    genelist = []
#    for gene in genes:
#        
#        genelist.append('hsa:%s' % gene['id'])
##        print gene['id']
#    gene_url = '+'.join(genelist)
#    url = '/conv/ncbi-geneid/%s' % (gene_url)
#    results = kegg_rest_request(url)
    #print results
    
    
    #if request.method == 'GET':
    return render_to_response('pathway_analysis/view.html', {'pathway':pathway}, context_instance=RequestContext(request)) 
Example 28
Project: django-angularjs-blog   Author: bluedazzle   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def index(req):
    return render_to_response('index.html') 
Example 29
Project: django-angularjs-blog   Author: bluedazzle   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def code(req):
    return render_to_response('code.html') 
Example 30
Project: django-angularjs-blog   Author: bluedazzle   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def lab(req):
    return render_to_response('lab.html')