问题处理上传文件django

时间:2011-05-03 11:22:53

标签: django file-upload django-forms django-views

我正在尝试执行一项允许用户上传文件的功能。该文件将有信息插入数据库,这就是为什么在函数中我保存数据。不确定这是否是最好的选择。

到目前为止我做了什么:

forms.py:

class UploadFileForm(forms.Form):
    file = forms.FileField()

的观点:

def last_step(request, word):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            msg = handle_uploaded_file(word, request.FILES['file'])
            return render_to_response('final_insert.html', {'msg': msg})
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', 
                               {
                                'word': word,
                                'form': form })

模板:

<form enctype="multipart/form-data" action="{% url upload_done 'clinical' %}" method="post">
<div>
    {% for field in form %}
        {{ field }}
    {% endfor %} 
    <input type="submit" value="Save" />
</div>
</form>

功能:

def handle_uploaded_file(word, f):
    msg = "first stop" 
    data = []
    for chunk in f.chunks():
        data.append(chunk)
    msg = "after chunk"    

    if word == 'clinical':
        pat = Patient.objects.values_list('patient', flat=True)
        for i in data:
            if i[0] not in pat:
                b2 = Patient(patient=i[0])
                b2.save()
                msg = "number was inserted"
            else:
                msg = "something"

    return msg       

问题是当我在模板中点击“保存”时,它会很好地重定向到另一个模板,但我没有看到任何消息,就像我想看到的那样(final_insert.html显示{{msg}})

有人能帮我理解我做错了什么吗? 欢迎任何帮助! 谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

我能理解我的错误 抱歉,我的愚蠢错误

所以这是形式:

<form enctype="multipart/form-data" action="{% url upload_done 'clinical' %}" method="post">
<div>
    {% for field in form %}
        {{ field }}
    {% endfor %} 
    <input type="submit" value="Save" />
</div>
</form>

网址:

url(r'^insert/file/(?P<word>clinical)/upload/$', last_step, name="upload"),
url(r'^insert/file/(?P<word>clinical)/upload/result/$', final, name='upload_done'),

所以视图last_step对应于网址“upload”而不是“upload_done”
我写了表格action = {%url upload_done'clinical'%},所以当我点击保存它会自动重定向到另一个模板。没有运行代码!!

所以我将表单更改为:

<form enctype="multipart/form-data" action="{% url upload 'clinical' %}" method="post">
<div>
    {% for field in form %}
        {{ field.label_tag }}
        {{ field }}
    {% endfor %} 
    <input type="submit" value="Guardar" />
</div>
</form>

现在它有效..

抱歉,伙计们,我以为我需要重定向到另一个页面但是当他重定向时他不会运行代码..