简体   繁体   English

django使用formset从上传的文件中获取文件名

[英]django get filename from uploaded file using formset

I'm trying to get the filename of an uploaded file, using formsets. 我正在尝试使用表单集获取上载文件的文件名。

views.py 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 forms.py

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

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

photoform['photo'] doesn't give me the filename directly, rather something like photoform['photo']不会直接给我文件名,而是类似

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

which doesn't list filename 没有列出filename

I've tried 我试过了

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'}

and I see the name there, but there's gotta be an easier way to get to it. 我在这里看到了名字,但是必须有一个更简单的方法来使用它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM