Scenario
I have two forms. In my case, I want to submit a second form through a modal, while being in the first form template. Instead of this, modal pops up as it should be when I click the link, but when I hit the submit button, the modal form is not submitted, but the main form is. I created a minimized project that simulates the problem.
Code
# models.py
class TestModel1(models.Model):
name = models.CharField(max_length=20)
class TestModel2(models.Model):
name = models.CharField(max_length=20)
# forms.py
class TestModel1Form(forms.ModelForm):
class Meta:
model = TestModel1
fields = ["name", ]
class TestModel2Form(forms.ModelForm):
class Meta:
model = TestModel2
fields = ["name", ]
# views.py
class TestModel1Create(CreateView):
model = TestModel1
form_class = TestModel1Form
template_name = 'mytestapp/testmodel1_form.html'
success_url = '/testmodel1/create'
class TestModel2Create(CreateView):
model = TestModel2
form_class = TestModel2Form
template_name = 'mytestapp/testmodel2_form.html'
success_url = '/testmodel1/create'
Here is the "main" form, testmodel1_form.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script>
<a href="/testmodel2/create/" class='li-modal'>Goto form 2</a>
<div id="theModal" class="modal fade text-center">
<div class="modal-dialog">
<div class="modal-content"></div>
</div>
</div>
<script>
$('.li-modal').on('click', function(e){
e.preventDefault();
$('#theModal').modal('show').find('.modal-content').load($(this).attr('href'));
});
</script>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
</body>
</html>
And here is the modal form, testmodel2_form.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
</body>
</html>
What I look for
The way I want this to work, is while being in the main form, POST the secondary form through the modal, and then get the main form reloaded.