Iam overriding the modeladmin when i try to save the many to many field in admin form iam getting this Foreinkey Error, if i didnt select it works.
#admin.py
def save_model(self, request, obj, form, change):
user = request.user
if not change:
_id = uuid.uuid4()
form_data = form.cleaned_data
data = {
'_id': _id,
'organisation': form_data['organisation'],
'project': form_data['project'],
'title': form_data['title'],
'description': form_data['description'],
'reporting_timestamp': form_data['reporting_timestamp']
}
files = form_data['attachments']
obj = controllers.incident.create(data, files, user, request)
return
#incident.py
def create(data, files, user, request):
incident = Incident.objects.create(
**data,
reporter=user
)
incident.state = 'OPEN'
print("files", files)
if files is not None:
incident = save_attachment(
files=files,
instance=incident
)
incident.save()
parameters = {
'user': str(user),
'_id': str(incident._id)
}
log_event(
action='ims.incident.create',
parameters=parameters
)
return incident
#save_attachment function in controllers.py
def save_attachment(files, instance):
"""
Saves multiple file attachments and associates many-to-many relation
with a specific model instance.
Parameters
----------
files : list of file-like objects
List of files to be attached.
instance : Model instance
The model instance to which the files are being attached.
Returns
-------
None
"""
if instance._id is None:
instance.save()
attachments = []
for file in files:
attachment, created = Attachment.objects.get_or_create(file=file)
attachment.save()
attachments.append(attachment)
instance.attachments.add(*attachments)
return instance