问题
I would like to know whether it is possible to divide the request.POST attribute in django in order to fill 2 or more distinct forms. Because my Main model operates in a form that it is related to 2 child models with a ManyToManyField(), I want to create more instances of this model using forms. A quick Example:
class ChildModelOne(models.Model):
title_one = models.CharField(max_length = 64)
list = models.ManyToManyField(otherModel, blank = True, default = None)
def __str__(self):
return self.title_one
class ChildModelTwo(models.Model):
title_two = models.CharField(max_length = 64)
list = models.ManyToManyField(otherModel, blank = True, default = None)
def __str__(self):
return self.title_two
class ParentModel(models.Model):
name = models.CharField(max_length = 128, default = 'My Name', null = True, blank = True)
p_modelOne = models.ForeignKey(ChildModelOne, on_delete = models.CASCADE,default = None, blank = True, null = True )
p_modelTwo = models.ForeignKey(ChildModelTwo, on_delete = models.CASCADE,default = None, blank = True, null = True )
and now my forms:
class Register_ChildModelOne(forms.ModelForm):
class Meta:
model = ChildModelOne
fields = ['title_one', 'list']
class Register_ChildModelTwo(forms.ModelForm):
class Meta:
model = ChildModelTWo
fields = ['title_two', 'list']
class Register_ParentModel(forms.ModelForm):
class Meta:
model = Routine
fields = [ 'name','p_modelOne', 'p_modelTwo']
and in my templates the forms are inherited as follows :
context {
'form_One' : Register_ChildModelOne(),
'form_Two' : Register_ChildModelTWo(),
}
when I try the basic:
if request.method == "POST":
form = Register_ParentModel(request.POST)
if form.is_valid():
form.save()
This saves my ParentModel() class but it is completely blank. I believe this happens because for a ParentModel() to get saved there needs to be saved a ChildModelOne() and a ChildModelTwo() instance.
Can Anyone help me how to distinguish the request.POST in this case into 2 distinct forms and then saving the New ParentModel() by passing those two as parameters in an array? I'm not quite sure for this method so if anyone suggests something easier and more beautiful I would appreciate it a lot.
来源:https://stackoverflow.com/questions/64839675/how-can-i-divide-the-request-post-to-fit-2-distinct-forms-in-django