用django上传文件的问题。

时间:2022-09-19 07:28:43

I'm new using django. I've to upload a file and fot this I'm following the instructions present in official documentation: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/?from=olddocs
my index.htlm

我刚使用django。我必须上传一个文件,并按照官方文档中的说明:http://docs.djangoproject.com/en/dev/topics/http/file-uploads/?从= olddocs index.htlm

    <form action="upload_file" enctype="multipart/form-data" method="POST">
        {% csrf_token %}
        <input type="file" name="upfile" size="30">
        <input type="submit" name="upfile" value= " Upload ">
    </form> 

my views.py:

我的views.py:

def handle_uploaded_file(f):
    destination = open('/my_path_to_tmp/tmp_files/input_file', 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()
    if ( f.file_name.endswith("sdf") ):
        return "sdf"
    elif ( f.file_name.endswith("smi") ):
        return "smi"

def upload_file(request):
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            file_type = handle_uploaded_file(request.FILES['upfile'])
            return HttpResponseRedirect('calculate', file_type)
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', {'form': form})

my urls.py

我的urls . py

urlpatterns = patterns('myapp.views',
    (r'^upload_file$', 'upload_file'),   
    (r'calculate/$', 'calculation'),
)

Really I don't know what I'm doing wrong here but it seems that the condition

我真的不知道我在这里做错了什么,但情况似乎是这样的。

if request.method == "POST":

in views.py fails. Even if the method="POST" to the html form.

Anybody has an idea?
Thank you so much!

在视图。py失败。即使方法="POST"到html表单。有人有一个想法吗?谢谢你这么多!

2 个解决方案

#1


1  

Are you sure that your form action is correct?

你确定你的表单动作是正确的吗?

Shouldn't it be something like this instead:

难道不应该是这样:

<form action="{% url upload_file %}" enctype="multipart/form-data" method="post">

#2


0  

You could perhaps output the request.method at the beginning of your method, just to be sure... after that, print form._errors.

您可以输出请求。方法在你的方法的开始,只是为了确定…之后,打印form._errors。

#1


1  

Are you sure that your form action is correct?

你确定你的表单动作是正确的吗?

Shouldn't it be something like this instead:

难道不应该是这样:

<form action="{% url upload_file %}" enctype="multipart/form-data" method="post">

#2


0  

You could perhaps output the request.method at the beginning of your method, just to be sure... after that, print form._errors.

您可以输出请求。方法在你的方法的开始,只是为了确定…之后,打印form._errors。