如何将模板脚本中变量的值发送到Django中的url?

时间:2019-04-02 01:55:22

标签: python django jsp

在django中,我想通过将任何变量的值放在模板的TAG值中来处理{%url%}。

pp_001.html

<script>
$('#dataTables-wkgrid tbody').on( 'click', 'tr', function () {
    var data = table.row( this ).data();
    if ( $(this).hasClass('selected') ) {
       $(this).removeClass('selected');
    }
    else {
       table.$('tr.selected').removeClass('selected');
       $(this).addClass('selected');
       $.ajax({
       type: "GET",
       url: "{% url 'pp_02_open' %}",
       data : {
           "cPp_no" : data.pp_no
       },
       dataType: "json",
       cache: false,
       success: function(result){
       console.log(result) ;
       var aTag = "" ;
       $.each(result.filelist,function(index){
       cDocName  = result.filelist[index].doc_name ;                                 
       cFilename = result.filelist[index].file_name ;
       cid  = result.filelist[index].id  ;
       cpp_no = result.filelist[index].pp_no ;
       aTag += '<a href="{% url "pp_02_download" id=cid %}" class="list-group-item">'
            +'<i name="iText" class="fa fa-file-powerpoint-o fa-fw"></i>'+result.filelist[index].doc_name
            +'<i name="file_downloads" class="pull-right glyphicon glyphicon-cloud-download style="padding-left:10px">다운로드</i>'                      
            +'</span>'
            +'</a>'

</script>

urls.py

    path(r'^PP/download/<int:id>/$' , views_pp.download , name="pp_02_download"),

错误......

找不到带有关键字参数'{'id':``}''的'pp_02_download'反向。尝试了1个模式:['crms / \ ^ PP \ / download \ /(?P [0-9] +)\ / \ $$']

换句话说,当jsp脚本的变量值是 {%url“ pp_02_download id = cid%},我想知道如何传递cid的值。

如果您以这种方式随机传递“ 10”而不是cid,它将正常执行。

2 个答案:

答案 0 :(得分:0)

发展尚未完成。首先,它在参数中获取id值,检索数据,然后尝试下载文件。

当前源配置为能够通过仅指定特定文件来检查下载是否正常。

views.py

def download(request,id):
    # filename = 'files/test.py'
    filename = 'files/테스트.pptx'
    file_path = os.path.join(settings.MEDIA_ROOT, filename)
    # file_path = reduce(os.path.join, (settings.MEDIA_ROOT, filename))
    logger.info('file_path : %s' , file_path )
    if os.path.exists(file_path) and os.path.isfile(file_path):
        with open(file_path, 'rb') as fp:
            response = HttpResponse(fp.read())
        content_type, encoding = mimetypes.guess_type(filename)
        if content_type is None:
            content_type = 'application/octet-stream'
        # content_type = ""
        response['Content-Type'] = content_type
        response['Content-Length'] = str(os.stat(file_path).st_size)
        logger.info('content_type : %s' , content_type )

    # encoding = 'euc-kr'
    logger.info("encoding : %s" , encoding )
    if encoding is not None:
        response['Content-Encoding'] = encoding
    else:
        response['Content-Encoding'] = 'euc-kr'

    if u'WebKit'in request.META.get('HTTP_USER_AGENT', u'Webkit'):
        filename = os.path.basename(filename)
        filename_header = 'filename=%s' % os.path.basename(filename)
    elif u'MSIE' in request.META.get('HTTP_USER_AGENT', u'MSIE'):
        filename_header = ''
        filename_header = 'filename=%s' % os.path.basename(filename)
    else:
        filename_header = 'filename=%s' % os.path.basename(filename)

    filename_header = filename_header.encode('cp949')   # utf -> euc 로 변환

    response['Content-Disposition'] = filename_header
    logger.info('filename-header : %s ' , filename_header )
    logger.info('[Content-Disposition] : %s' , response['Content-Disposition'])

    return response

答案 1 :(得分:0)

#!/usr/bin/env python3

import pandas as pd
from flask import Flask, render_template, session
import os

app = Flask(__name__)


app.secret_key = os.urandom(28)


@app.route('/first_page', methods=['GET', 'POST'])
def first_page():
    d = {'products': ['pencils', 'pens', 'erasers'], 'id_code': ['1_2', '10_7', '12_11']}
    df = pd.DataFrame(d)
    print(df)
    session["data"] = df.to_json()
    return render_template('/private/test_page1.html')

@app.route('/second_page', methods=['GET', 'POST'])
def second_page():
    dat = session.get('data')
    dat = pd.read_json(dat, dtype=False)
    print(dat)
    return render_template('/private/test_page2.html')




if __name__ == '__main__':
    app.run(port=5001,debug=True)

console output:

127.0.0.1 - - [01/Apr/2019 23:38:56] "GET / HTTP/1.1" 404 -
  products id_code
0  pencils     1_2
1     pens    10_7
2  erasers   12_11
127.0.0.1 - - [01/Apr/2019 23:39:03] "GET /first_page HTTP/1.1" 200 -
  products id_code
0  pencils     1_2
1     pens    10_7
2  erasers   12_11

对urls.py的更改将不起作用。

在/ crms / PP /下的NoReverseMatch 找不到带有关键字参数'{'id':''}'的'pp_02_download'。尝试了1种模式:['crms / PP \ / download \ /(?P [0-9] +)\ / $']