In my recent project I had to create a generic model with a single file field, because the idea was to use multiple file uploads across multiple system models.
For this I created this generic model with generic foreign key and in the add view I create a formset with the extra = 1 field and in the template via jquery I add forms inside my formset.
In addition it works quietly, but I'm not able to adjust my edit view.
In my edit view I try it:
ModelGenericFormset = modelformset_factory(
ModelsFileGeneric,
form=AddModelsGenericForm
)
query_files = ModelsFileGeneric.objects.filter(
object_id=model_related_to_generic_model_with_file_field.id,
)
files = ModelGenericFormset(queryset=query_files)
and in request.post:
files_form_set = ModelGenericFormset(
request.POST,
request.FILES
)
for file_form in files_form_set:
file = file_form.save(commit=False)
setattr(
'upload_destination',
'path_to_upload'
)
file.content_object = model_related_to_generic_model_with_file_field
file.save()
An observation: As this model where the file field is is an extremely generic model (for this reason the use of the generic foreign key), I also need at runtime (in the save in view after the post) to change the upload_to attribute of the field (this already Was fixed and works ok). I make this edition of the "upload_to" attribute because depending on the model to which I am sending multiple files, it will vary the path from where the files will be saved.
But in save of the edit view this error occurs:
The ModelsFileGeneric could not be changed because the data didn't validate.
And the error is in:
file = file_form.save(commit=False)
I don't know what to do anymore. Thanks!