避免Django剥离文本文件上传



我曾被要求将Python应用程序转换为Django应用程序,但我对Django完全陌生。

我有以下问题,当我上传一个文件文本,必须读取以保存其内容到数据库中时,我发现Django正在剥离"额外的"空白,我必须保留这些空白。

这是我的模板

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Test</title>
</head>
<body>
    {% if newdoc %}
        <ul>
        {% for line in newdoc %}
            <li>{{ line }} </li>
        {% endfor %}
        </ul>
    {% endif %}
    <form action="{% url 'exam:upload' %}" method="post" enctype="multipart/form-data" content-type="text/plain">
        {% csrf_token %}
            <p>{{ form.non_field_errors }}</p>
            <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
            <p>
                    {{ form.docfile.errors }}
                    {{ form.docfile }}
            </p>
        <p><input type="submit" value="Upload" /></p>
    </form>
</body>

这是我在views。py

中的内容
def upload(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = request.FILES['docfile']
            form = DocumentForm()
            return render(request, 'exam/upload.html', {'newdoc': newdoc, 'form': form})
    else:
        form = DocumentForm() # A empty, unbound form
    return render(request, 'exam/upload.html', {
        'form': form,
    })

这是form。py:

from django import forms
class DocumentForm(forms.Form):
    docfile = forms.FileField(
        label='Select a file',
        help_text='max. 42 megabytes'
)
现在,当我上传文件时,它显示了这样的随机行:
"09000021009296401 02 b a b a b b b d b b d d a +8589 +03+6942 +03+1461 +00+5093 +00+2 +00+9237 +01+60 +01+00 +00"

而它应该是这样的:

"09000021009296401 02 b   a          b   a     b    b    b d  b    b      d    d                a                        +8589  +03+6942  +03+1461  +00+5093  +00+2     +00+9237  +01+60    +01+00    +00                    "

我必须保留额外的空格,他们将这些信息保存到数据库中,如果我没有文件中所有的空格,我就不能正确地做到这一点。

另外,在你问之前,它与Django的打印格式无关,因为在之前的测试中,我已经尝试将信息保存到模型中,但它与空格有相同的问题。

谢谢大家。

按如下方式修改模板:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Test</title>
</head>
<body>
    {% if newdoc %}
    <pre><code>{% for line in newdoc %}{{ line|safe }}{% endfor %}</code></pre>
    {% endif %}
    <form action="{% url 'exam:upload' %}" method="post" enctype="multipart/form-data" content-type="text/plain">
        {% csrf_token %}
            <p>{{ form.non_field_errors }}</p>
            <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
            <p>
                    {{ form.docfile.errors }}
                    {{ form.docfile }}
            </p>
        <p><input type="submit" value="Upload" /></p>
    </form>
</body>

最新更新