简体   繁体   English

如何从Django模板语言获取表单数据

[英]How to get form data from django template language

I'm new to Django, I'm currently iterate through a filtered QuerySet and post the results as a string on my website using {{file.filename}} . 我是Django的新手,我目前正在遍历经过过滤的QuerySet,并使用{{file.filename}}将结果作为字符串发布在我的网站上。 I'm having trouble getting that filename from a double click. 我无法通过双击获取该文件名。

$('.file').dblclick(function () {
    $.post('/accounts/download/', $(this).attr('id'));
});

The HTML I have is 我拥有的HTML是

{% for file in file_info %}
<p id= {{ file.filename }} class='file'>{{ file.filename }}</p>
{% endfor %}

I'm confused if setting the id this way is the correct way to get the filename. 如果通过这种方式设置id是获取文件名的正确方法,我感到困惑。

My view receives the request: 我的视图收到了请求:

def download(request):
    person = request.user.id
    form = Download_Form(request.POST)
    print form
    file_name = form['file_name'].value()
    print file_name
    return render(request, 'main.html')

And the following print statements above are 上面的以下打印语句是

<tr><th><label for="id_file_name">File name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input id="id_file_name" maxlength="300" name="file_name" type="text" /></td></tr>

None

I understand that I can't add .value() to form['file_name'] , but I'm not sure how to retrieve that file data. 我知道我无法将.value()添加到form['file_name'] ,但是我不确定如何检索该文件数据。

You are not passing the name of your POST variable (ie file_name ) to the page. 您没有将POST变量的名称(即file_name )传递给页面。 Try changing that line to: 尝试将该行更改为:

$.post('/accounts/download/', {file_name: $(this).attr('id')});

It is also a good idea to use quotation marks for the id attributes: id属性使用引号也是一个好主意:

<p id="{{ file.filename }}" class="file">{{ file.filename }}</p>

Then you can simply access the file_name using the request.POST dictionary. 然后,您可以使用request.POST词典简单地访问file_name You don't have to instantiate a Django form: 您不必实例化Django表单:

@csrf_exempt
def download(request):
    ...
    print request.POST.get('file_name')
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM