在django中将变量从模板传递到视图

时间:2019-03-27 10:16:54

标签: django django-views django-urls

在每个位置上单击时,我必须从那里获取一个文本文件。我需要将这些位置传递给views.py来呈现文件。

模板:

<script>
if(data.columns[j] == "outputFilePath"){
    var op = JSON.stringify(data.tableData[i][j]);
    op = op.substring(1, op.length-1)
    row.append("<td><a href='/dhl/outputDir'>" + op + "</a></td>")
}
</script>

意见。 py:

def outputDir(request,location):
    text_data = open("location/stdout", "rb").read()
    return HttpResponse(text_data, content_type="text/plain")

urls.py

url(r'^dhl/outputDir',views.outputDir),

1 个答案:

答案 0 :(得分:0)

您可以通过传递参数来使用基本模板标签和默认视图功能。

但是,您要实现的目标将使该视图向所有人打开,以便任何人都可以通过输入所需的任何文件夹来访问应用程序中的文件夹。您可以添加一个允许的位置列表,这是我在下面的解决方案中所做的。

模板

if(data.columns[j] == "outputFilePath"){
    var op = JSON.stringify(data.tableData[i][j]);
    op = op.substring(1, op.length-1)
    row.append("<td><a href='/dhl/outputDir/" + op + "'>" + op + "</a></td>")
}

views.py

def outputDir(request, location):
    # Make sure to check if the location is in the list of allowed locations
    if location in allowed_locations:
        text_data = open(location + "/stdout", "rb").read()
        return HttpResponse(text_data, content_type="text/plain")
    else:
        return PermissionDenied

您还需要向网址添加参数:

urls.py

url(r'^dhl/outputDir/(?P<location>\w+)', views.outputDir),
相关问题