【问题标题】:Problems in uploading files with djangodjango上传文件的问题
【发布时间】:2011-07-08 16:50:02
【问题描述】:

我是使用 django 的新手。我必须上传一个文件并按照官方文档中的说明进行操作: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/?from=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> 

我的意见.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})

我的 urls.py

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

我真的不知道我在这里做错了什么,但似乎条件

if request.method == "POST":

在views.py 中失败。即使method="POST" 到html 表单。

有人有想法吗?
非常感谢!

【问题讨论】:

    标签: python django file-upload django-views


    【解决方案1】:

    您确定您的表单操作正确吗?

    不应该是这样吗:

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

    【讨论】:

    • 好吧,我不确定。我没有使用 django 的经验。如果我尝试按照你说的做,我会收到以下错误:TemplateSyntaxError: Caught NoReverseMatch while rendering: Reverse for 'upload_file' with arguments '()' and keyword arguments '{}' not found.
    • 是的,那只是因为你的 url 文件应该是这样的:urlpatterns = patterns('myapp.views', (r'^upload_file$', 'upload_file' name='upload_file'), (r'calculate/$', 'calculation', name='calculation'), )
    • 好的,谢谢。如果我按照 fylb 的说明进行修改,我会在“name=" 的 urls.py 文件中获得“SyntaxError: invalid syntax”
    • @green69: 用'calculation'代替name='calculation',其他的也一样。
    【解决方案2】:

    您也许可以在方法的开头输出 request.method,以确保...之后,打印 form._errors。

    【讨论】:

    • 感谢您帮助我。实际上似乎 request.method == "POST" 但 request.POST 是空的。这怎么可能?
    猜你喜欢
    • 1970-01-01
    • 2011-11-01
    • 2011-07-09
    • 2011-08-17
    • 2012-06-04
    • 2011-04-24
    • 2011-10-06
    • 2020-09-12
    • 2015-07-05
    相关资源
    最近更新 更多