python - 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'}
我在那里看到了名字,但必须有更简单的方法才能找到它。
解决方案
最终起作用的是
print(photoform.cleaned_data.get('photo').name)
推荐阅读
- javascript - 通过常量为交互元素分配角色
- javascript - 历史推送状态重定向,而不是仅仅将新状态推送到浏览器历史
- hibernate - 在spring mvc中处理连续请求
- java - 收到 javax.crypto.IllegalBlockSizeException 错误:使用填充密码解密时输入长度必须是 8 的倍数
- pdf - 在 WebView 中渲染 PDF 和 DOC 文件 - 两者都可以作为 URL 或文件 - Android
- visual-studio-2017 - VS Professional 2017 - 15.9.11 - 与安装相关的问题
- android - 如何在 android.bp 中编写条件 ifeq ($(filter-out tt_%,$(TARGET_PRODUCT)),)
- javascript - 使用构造函数比较对象内部的值
- symfony - 在教义中使用间隔时出错
- google-apps-script - Google Apps Script script.run -- 得到意外的 401,即使在发送 Oauth 令牌时也是如此