1
0
mirror of https://github.com/django/django.git synced 2025-10-23 21:59:11 +00:00

Fixed #35384 -- Raised FieldError when saving a file without a name to FileField.

This commit is contained in:
Jonny Park
2024-04-28 11:54:54 +09:00
committed by Sarah Boyce
parent b691accea1
commit c0b0ce85ed
3 changed files with 39 additions and 2 deletions

View File

@@ -3,7 +3,8 @@ import posixpath
from django import forms
from django.core import checks
from django.core.files.base import File
from django.core.exceptions import FieldError
from django.core.files.base import ContentFile, File
from django.core.files.images import ImageFile
from django.core.files.storage import Storage, default_storage
from django.core.files.utils import validate_file_name
@@ -12,6 +13,7 @@ from django.db.models.fields import Field
from django.db.models.query_utils import DeferredAttribute
from django.db.models.utils import AltersData
from django.utils.translation import gettext_lazy as _
from django.utils.version import PY311
class FieldFile(File, AltersData):
@@ -312,6 +314,15 @@ class FileField(Field):
def pre_save(self, model_instance, add):
file = super().pre_save(model_instance, add)
if file.name is None and file._file is not None:
exc = FieldError(
f"File for {self.name} must have "
"the name attribute specified to be saved."
)
if PY311 and isinstance(file._file, ContentFile):
exc.add_note("Pass a 'name' argument to ContentFile.")
raise exc
if file and not file._committed:
# Commit the file to storage prior to saving the model
file.save(file.name, file.file, save=False)