1

当我提交一个具有 method="POST" 的表单时,处理它的视图正在获取方法 GET,我似乎无法让它成为文件上传所必需的 POST。只是罐装我现有的(一周前工作,在升级到 1.4 之前)并尝试使用从https://docs.djangoproject.com/en/dev/topics/http/file-uploads/上传示例的表格,你能看出这里出了什么问题吗?我尝试使用 Chrome Incognito 进行新会话,结果相同。当我不包含 method="POST" 时,它使用方法 GET 提交,并且这些字段包含在电子邮件的 request.GET 字典中。但是,当我更改为 POST/post 时,它仍然是 GET 方法,并且字段不在 request.POST 或 request.GET 字典中。Django 1.4 中是否存在导致此行为的错误?有什么我想念的吗?我试图做一个简单的例子来排除所有无关的潜在变量。

简单的测试场景:

网址.py:

url(r'^upload_test/+$', 'views.presentation.UploadTest'),
url(r'^uploaded_test/+$', 'views.presentation.UploadedTest'),

意见/presentation.py:

def Notify(subject, body):
    """
        Send an email to <to_email>, from <from_email> with the
        subject and body supplied.
    """
    send_mail(subject, body, '<from_email>', ['<to_email>'], fail_silently=False)

def UploadTest(request):
    Notify("UploadTest", "METHOD: " + str(request.method) + """

    """ + str(request))
    return render_to_response('upload.htm', context_instance=RequestContext(request))

def UploadedTest(request):
    Notify("UploadedTest", "METHOD: " + str(request.method) + """

    """ + str(request) + """

    FILES:
    """ + str(request.FILES))
    return render_to_response('upload.htm', context_instance=RequestContext(request))

upload.htm(注意方法是POST,我也尝试了小写以防万一):

<form
    id="upload_file_form"
    action="/uploaded_test"
    method="POST"
    enctype="multipart/form-data"
    target="_blank"
>
    {% csrf_token %}
    <input type="text" name="extra_field" value="extra post field" />
    <input type="file" name="upload_file" id="upload_file" />
    <input type="submit" name="upload" value="Submit" />
</form>

简单测试场景的结果

我收到的电子邮件(注意第一个是预提交的表单,第二个是发布的表单页面):

第一封电子邮件(主题“UploadTest”):

METHOD: GET

<WSGIRequest
    path:/upload_test/,
    GET:<QueryDict: {}>,
    POST:<QueryDict: {}>,
    COOKIES:{
        'csrftoken': '...',
        'sessionid': '...'},
    META:{'CSRF_COOKIE': '...',
    'DOCUMENT_ROOT': '...',
    'GATEWAY_INTERFACE': 'CGI/1.1',
    'HTTPS': '1',
    'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'HTTP_ACCEPT_ENCODING': 'gzip, deflate',
    'HTTP_ACCEPT_LANGUAGE': 'en-us,en;q=0.5',
    'HTTP_CONNECTION': 'keep-alive',
    'HTTP_COOKIE': '... csrftoken=...; CFID=16005; CFTOKEN=...; sessionid=...',
    'HTTP_HOST': '...',
    'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:11.0) Gecko/20100101 Firefox/11.0',
    'PATH_INFO': u'/upload_test/',
    'PATH_TRANSLATED': '...site.wsgi/upload_test/',
    'QUERY_STRING': '',
    'REMOTE_ADDR': '10.1.0.100',
    'REMOTE_PORT': '56037',
    'REQUEST_METHOD': 'GET',
    'REQUEST_URI': '/upload_test/',
    'SCRIPT_FILENAME': '...site.wsgi',
    'SCRIPT_NAME': u'',
    'SERVER_ADDR': '10.1.10.12',
    'SERVER_ADMIN': '...',
    'SERVER_NAME': '...',
    'SERVER_PORT': '443',
    'SERVER_PROTOCOL': 'HTTP/1.1',
    'SERVER_SIGNATURE': '',
    'SERVER_SOFTWARE': 'Apache',
    'SSL_TLS_SNI': '...',
    'mod_wsgi.application_group': '...|',
    'mod_wsgi.callable_object': 'application',
    'mod_wsgi.handler_script': '',
    'mod_wsgi.input_chunked': '0',
    'mod_wsgi.listener_host': '',
    'mod_wsgi.listener_port': '443',
    'mod_wsgi.process_group': '',
    'mod_wsgi.request_handler': 'wsgi-script',
    'mod_wsgi.script_reloading': '1',
    'mod_wsgi.version': (3, 3),
    'wsgi.errors': <mod_wsgi.Log object at 0x1962048>,
    'wsgi.file_wrapper': <built-in method file_wrapper of mod_wsgi.Adapter object at 0xb73d2770>,
    'wsgi.input': <mod_wsgi.Input object at 0x1962020>,
    'wsgi.multiprocess': True,
    'wsgi.multithread': True,
    'wsgi.run_once': False,
    'wsgi.url_scheme': 'https',
    'wsgi.version': (1, 1)}>

第二封电子邮件(主题“UploadedTest”,方法仍然是“GET”,注意 HTTP_REFERER 正确,并且 request.FILES 存在,但为空。):

METHOD: GET

<WSGIRequest
    path:/uploaded_test/,
    GET:<QueryDict: {}>,
    POST:<QueryDict: {}>,
    COOKIES:{
        'csrftoken': '...',
        'sessionid': '...'
    },
    META:{'CSRF_COOKIE': '...',
    'DOCUMENT_ROOT': '...',
    'GATEWAY_INTERFACE': 'CGI/1.1',
    'HTTPS': '1',
    'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'HTTP_ACCEPT_ENCODING': 'gzip, deflate',
    'HTTP_ACCEPT_LANGUAGE': 'en-us,en;q=0.5',
    'HTTP_CONNECTION': 'keep-alive',
    'HTTP_COOKIE': 'csrftoken=...; sessionid=...',
    'HTTP_HOST': '...',
    'HTTP_REFERER': '.../upload_test/',
    'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:11.0) Gecko/20100101 Firefox/11.0',
    'PATH_INFO': u'/uploaded_test/',
    'PATH_TRANSLATED': '...site.wsgi/uploaded_test/',
    'QUERY_STRING': '',
    'REMOTE_ADDR': '10.1.0.100',
    'REMOTE_PORT': '56040',
    'REQUEST_METHOD': 'GET',
    'REQUEST_URI': '/uploaded_test/',
    'SCRIPT_FILENAME': '...site.wsgi',
    'SCRIPT_NAME': u'',
    'SERVER_ADDR': '10.1.10.12',
    'SERVER_ADMIN': '...',
    'SERVER_NAME': '...',
    'SERVER_PORT': '443',
    'SERVER_PROTOCOL': 'HTTP/1.1',
    'SERVER_SIGNATURE': '',
    'SERVER_SOFTWARE': 'Apache',
    'SSL_TLS_SNI': '...',
    'mod_wsgi.application_group': '...|',
    'mod_wsgi.callable_object': 'application',
    'mod_wsgi.handler_script': '',
    'mod_wsgi.input_chunked': '0',
    'mod_wsgi.listener_host': '',
    'mod_wsgi.listener_port': '443',
    'mod_wsgi.process_group': '',
    'mod_wsgi.request_handler': 'wsgi-script',
    'mod_wsgi.script_reloading': '1',
    'mod_wsgi.version': (3, 3),
    'wsgi.errors': <mod_wsgi.Log object at 0x1956b88>,
    'wsgi.file_wrapper': <built-in method file_wrapper of mod_wsgi.Adapter object at 0x21cf0f8>,
    'wsgi.input': <mod_wsgi.Input object at 0x1961048>,
    'wsgi.multiprocess': True,
    'wsgi.multithread': True,
    'wsgi.run_once': False,
    'wsgi.url_scheme': 'https',
    'wsgi.version': (1, 1)}>

    FILES:
    <MultiValueDict: {}>

值得怀疑,但我的 wsgi 文件或 Apache 站点指令中可能有问题。以下是这些,以防万一:

...wsgi:

import os
import sys

path = '/var'
if path not in sys.path:
   sys.path.append(path)

path = '/var/www'
if path not in sys.path:
   sys.path.append(path)

path = '/var/www/site'
if path not in sys.path:
   sys.path.append(path)

os.environ['DJANGO_SETTINGS_MODULE'] = 'site.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

启用 Apache 站点的指令:

<VirtualHost 10.1.10.12:80>
    ServerName ...
    RewriteEngine on
    RewriteCond %{HTTPS} !=on
    RewriteRule ^/(.*) https://%{SERVER_NAME}/$1 [R,L]
</VirtualHost>


<Directory /var/www/site>
    RewriteEngine on
    RewriteCond 1 =1
    RewriteRule ^/(.*) https://%{SERVER_NAME}
</Directory>


<VirtualHost 10.1.10.12:443>
    ServerName ...
    DocumentRoot /var/www/site
    ServerAlias ...
    ErrorLog /var/log/apache2/site-error.log
    LogLevel warn
    CustomLog /var/log/apache2/site-access.log combined
    WSGIScriptAlias / /var/www/site/site.wsgi
    SSLEngine on
    SSLCertificateFile ...
    SSLCertificateKeyFile ...

    # Media serving, must specify which files to serve and not
    # hand their urls to the django framework.
    Alias /robots.txt .../robots.txt
    Alias /favicon.ico .../favicon.ico

    Alias /templates/ .../django_templates/
    Alias /static/ .../django_static/
    Alias /images/ .../django_static/images/

    <Directory /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media/>
            Order deny,allow
            Allow from all
    </Directory>

    <Directory .../django_static/>
            Order deny,allow
            Allow from all
    </Directory>

    <Directory /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media/js>
            Order allow,deny
            Allow from all
    </Directory>

    <Directory .../uploads/>
            Order allow,deny
            Allow from all
    </Directory>

    XSendFile on

4

2 回答 2

2

也许我需要阅读更多关于 urls.py 或正则表达式的信息。我不小心将表单更改为action="uploaded_test"不带斜线的帖子,并收到一个 404 错误报告,其中 request.method 为“POST”(什么?!@#$*&)...???这意味着它必须与我的发布网址有关!我有它:

'^uploaded_test/+$'

我将其更改为:

'^uploaded_test$'

并验证该表格已发布到action="/uploaded_test"并且有效!我将 urls.py 更改为:

'^uploaded_test/$'

并将表格更改为发布到action="/uploaded_test/",它也有效!我的大多数 urls 条目中都有 /+,因此我可以接受 /loc 或 /loc/ 的许多条目。我想我现在会把它们改回来。我不知道这是一个错误还是我不了解正则表达式/+语法的东西。

于 2012-04-06T17:26:35.413 回答
1

您是否在表示层中尝试过 if-else 语句?例如if request.method == 'POST':,然后是您的其余代码。

于 2012-04-06T17:15:15.237 回答