首页 > 解决方案 > django 使用 formset 从上传的文件中获取文件名

问题描述

我正在尝试使用表单集获取上传文件的文件名。

视图.py

...
    elif request.method == 'POST':
        albumform = AlbumForm(request.POST)
        photoformset = PhotoFormSet(request.POST, request.FILES)

        if albumform.is_valid() and photoformset.is_valid():
            album = albumform.save(commit=False)
            album.user = request.user
            album.save()

            for photoform in photoformset:
                if photoform.is_valid() and photoform.has_changed():
                # here is where I'm lost

表格.py

...
class AlbumForm(forms.ModelForm):
    class Meta:
        model = Album
        fields = ('title', 'description')

PhotoFormSet = modelformset_factory(
    Photo,
    fields=('photo',),
    extra=4
)

photoform['photo']不直接给我文件名,而是像

<input type="file" name="form-0-photo" accept="image/*" id="id_form-0-photo">

没有列出filename

我试过了

photo = photoform.save(commit=False)
print(vars(photo))
{'_state': <django.db.models.base.ModelState object at 0x000001F6326132E8>, 'id': None, 'album_id': 105, 'name': '', 'photo': <ImageFieldFile: phone.png>, 'photo_width': 600, 'photo_height': 416, 'thumbnail': '', 'status': '1'}

我在那里看到了名字,但必须有更简单的方法才能找到它。

标签: pythondjangodjango-forms

解决方案


最终起作用的是 print(photoform.cleaned_data.get('photo').name)


推荐阅读