Answer the question
In order to leave comments, you need to log in
How to save a form into multiple objects?
There is a model in which ssh data is stored:
class Volumion(models.Model):
name = models.CharField(max_length=50)
hostname = models.CharField(max_length=50)
port = models.IntegerField()
user = models.CharField(max_length=30)
password = models.CharField(max_length=30)
is_online = models.BooleanField(default=False)
class Files(models.Model):
volumio = models.ForeignKey(Volumion, on_delete = models.CASCADE)
file = models.FileField(upload_to='uploads/')
name = models.CharField(max_length=100, blank=True, null=True)
if form.is_valid():
for vol in Volumion.objects.filter(is_online=True):
new = form.save(commit=False)
new.volumio_id = vol.id
new.set_name()
new.save()
Answer the question
In order to leave comments, you need to log in
ids = [p.id for p in Volumion.objects.filter(is_online=True)]
new = form.save(commit=False)
new.volumio_id = ids[0]
new.set_name()
new.save()
for id in ids[1:]:
Files.objects.create(volumio_id=id, file=new.file, name=new.name)
Crutch solution
In the form, we write a method that duplicates the creation:
def save_duplicate(self, volumion):
volumion.id = None
volumion.save()
Files.objects.create(**self.cleaned_data, volumio=volumion)
from copy import deepcopy
if form.is_valid():
for vol in Volumion.objects.filter(is_online=True):
new = form.save(commit=False)
new.volumio_id = vol.id
new.set_name()
new.save()
new.save_duplicate(deepcopy(vol))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question