【问题标题】:Adding a request variable in a Django template在 Django 模板中添加请求变量
【发布时间】:2017-08-29 22:45:30
【问题描述】:

我目前正在 Django 中将文件上传到服务器,如下所示(由于某些不相关的原因,我无法为该表单使用模型):

<div class="input-group" style="padding-top: 10px">
    <div><input class="form-control" id="filename" value="Select a ZIP file to upload..." disabled></div>
    <div class="input-group-btn"><input type="button" id="get_file" class="btn btn-primary" value="Browse"
                                                    style="margin-right: 3px;margin-left: 3px"></div>
    <div class="input-group-btn"><input type="submit" id="upload"
         class="btn btn-success" value="Upload" style="display: none"></div>
   <input type="file" id="upload_file" name="upload_file" accept=".zip">
</div>

然后我的一些 JavaScript 为:

document.getElementById('get_file').onclick = function() {
     document.getElementById('upload_file').click();
};

$('input[type=file]').change(function (e) {
     document.getElementById('filename').value = ($(this).val());
     document.getElementById('upload').style.display = "inline"
});

document.getElementById('upload').onclick = function() {
};

这工作正常,我可以上传文件就好了。但是,现在连同一个文件,我还想发送一个字符串标识符。我不确定如何在从该模板提交时插入另一个请求参数?

Django 这边是这样的:

def upload(request):
    """
    if request.method == 'POST' and request.FILES['upload_file']:
        # Do things

所以我需要添加另一个参数,以便我可以执行以下操作:request.GET.get('identifier') 并且这个identifier 键/值被插入到模板代码中。

【问题讨论】:

  • 嗨卢卡。我碰巧在你的个人资料上注意到,你喜欢用全小写的方式写标题,大概是出于文体原因。我能麻烦您改用句子大小写吗?网站上有很多编辑,他们自愿花时间整理内容并使其尽可能具有可读性,但如果可以减少创建的新作品的数量,这将极大地帮助他们(和我)!谢谢。
  • @halfer 当然可以。很抱歉!

标签: javascript django forms django-forms django-templates


【解决方案1】:

在表单中添加隐藏输入是否有效?

<input type="hidden" name="identifier" value="..."/>

【讨论】:

  • 感谢您的回复。不幸的是,在我看来,request.GET.get('studyid') 仍然返回 None。我加了:&lt;input type="hidden" name="studyid" value="Test"/&gt;
  • 当我写这篇文章的时候,我意识到我是多么的愚蠢!应该是request.POST.get(...)
猜你喜欢
  • 2011-07-10
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 2011-09-22
  • 1970-01-01
  • 2017-03-18
  • 2013-08-22
  • 1970-01-01
相关资源
最近更新 更多