diff --git a/django/test/client.py b/django/test/client.py index aea051ed2b..be5b6198bf 100644 --- a/django/test/client.py +++ b/django/test/client.py @@ -226,7 +226,12 @@ def encode_multipart(boundary, data): def encode_file(boundary, key, file): def to_bytes(s): return force_bytes(s, settings.DEFAULT_CHARSET) - filename = os.path.basename(file.name) if hasattr(file, 'name') else '' + + # file.name might not be a string. For example, it's an int for + # tempfile.TemporaryFile(). + file_has_string_name = hasattr(file, 'name') and isinstance(file.name, six.string_types) + filename = os.path.basename(file.name) if file_has_string_name else '' + if hasattr(file, 'content_type'): content_type = file.content_type elif filename: diff --git a/tests/test_client/tests.py b/tests/test_client/tests.py index d017fa42b1..7e5795b022 100644 --- a/tests/test_client/tests.py +++ b/tests/test_client/tests.py @@ -22,6 +22,8 @@ rather than the HTML rendered to the end-user. """ from __future__ import unicode_literals +import tempfile + from django.contrib.auth.models import User from django.core import mail from django.http import HttpResponse @@ -714,6 +716,11 @@ class ClientTest(TestCase): with self.assertRaisesMessage(Exception, 'exception message'): self.client.get('/nesting_exception_view/') + def test_uploading_temp_file(self): + test_file = tempfile.TemporaryFile() + response = self.client.post('/upload_view/', data={'temp_file': test_file}) + self.assertEqual(response.content, b'temp_file') + @override_settings( MIDDLEWARE=['django.middleware.csrf.CsrfViewMiddleware'], diff --git a/tests/test_client/urls.py b/tests/test_client/urls.py index ca8d5a8fc2..9f8d09218e 100644 --- a/tests/test_client/urls.py +++ b/tests/test_client/urls.py @@ -5,6 +5,7 @@ from django.views.generic import RedirectView from . import views urlpatterns = [ + url(r'^upload_view/$', views.upload_view, name='upload_view'), url(r'^get_view/$', views.get_view, name='get_view'), url(r'^post_view/$', views.post_view), url(r'^trace_view/$', views.trace_view), diff --git a/tests/test_client/views.py b/tests/test_client/views.py index 2761f19e80..6e7d3a37d5 100644 --- a/tests/test_client/views.py +++ b/tests/test_client/views.py @@ -324,3 +324,8 @@ def nesting_exception_view(request): def django_project_redirect(request): return HttpResponseRedirect('https://www.djangoproject.com/') + + +def upload_view(request): + """Prints keys of request.FILES to the response.""" + return HttpResponse(', '.join(request.FILES.keys()))