Почему django class-based_view не видит мои загрузки?
class MultipleFileInput(forms.ClearableFileInput):
"""
Work around for `widget=forms.ClearableFileInput(attrs={'multiple': True})`
>> `widget=MultipleFileInput(attrs={'multiple': True})`
"""
input_text = 'Select'
clear_checkbox_label = 'Clear'
initial_text = 'Current'
allow_multiple_selected = True
class UserUploadForm(forms.ModelForm):
file = forms.FileField(
widget=MultipleFileInput(attrs={'multiple': True}),
required=True,
validators=[FileExtensionValidator(allowed_extensions=['csv'])],
)
class Meta:
model = UserUpload
fields = ['file']
class MyFilesView(FormView):
template_name = 'data_related/my_files.html'
form_class = UserUploadForm
success_url = reverse_lazy('my_files')
def post(self, request, *args, **kwargs):
self.object = None
form = self.get_form()
files = self.request.FILES.getlist('file')
print(files)
print("Files received:", request.FILES.getlist('file')) # Debug output to confirm files are received
if form.is_valid():
print("Form is valid") # Debug statement
return self.form_valid(form)
else:
print("Form is not valid") # Debug statement
for field, errors in form.errors.items():
for error in errors:
print(f"Error in {field}: {error}")
messages.error(request, f"Error in {field}: {error}")
return self.form_invalid(form)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user_files = UserUpload.objects.filter(user=self.request.user)
files = [{'short_name': file.file.name, 'file_size': file.file_size, 'uuid': file.uuid} for file in user_files]
# Pagination
paginator = Paginator(files, 10) # Show 10 files per page
page_number = self.request.GET.get('page')
page_obj = paginator.get_page(page_number)
context.update({
'user_files': files,
'page_obj': page_obj,
'form': self.get_form(), #form_class((self.request.POST, self.request.FILES) or None) # show UserUploadForm, must instantiate form with POST and FILES
})
2024-04-26 03:53:45 []
2024-04-26 03:53:45 Files received: []
2024-04-26 03:53:45 Form is not valid
2024-04-26 03:53:45 Error in file: This field is required.
2024-04-26 03:53:56 [<InMemoryUploadedFile: geographies.csv (text/csv)>]
2024-04-26 03:53:56 Files received: [<InMemoryUploadedFile: geographies.csv (text/csv)>]
2024-04-26 03:53:56 Form is not valid
2024-04-26 03:53:56 Error in file: No file was submitted. Check the encoding type on the form.
Эта штука просто сумасшедшая. Я загружал файлы, и он сказал, что нашел мои файлы, но при этом отказался подтвердить форму загрузки.
Эта проблема связана с этой темой Не был отправлен файл. Проверьте тип кодировки на форме, и я сделал все, что там указано.