我正在尝试使用表单集获取上传文件的文件名。
views.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
forms.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'}
我在这里看到了名字,但是必须有一种更简单的方法来获得它。
答案 0 :(得分:1)
最终起作用的是
print(photoform.cleaned_data.get('photo').name)