将变量从模板传递到 Django 中的视图

pass variables from template to views in django

点击每个位置后,我必须从那里获取一个文本文件。我需要将这些位置传递给 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),

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

但是,您要实现的目标是让任何人都可以通过输入他们想要的任何文件夹来访问应用程序中的文件夹。您可以添加允许的位置列表,我在下面的解决方案中已经这样做了。

模板

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

您还需要在 url 中添加一个参数:

urls.py

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