Hello, I’m starting to use Django 5 and I’m building a web project for a Secret Santa draw. For that, I created the following model:
python
class Draw(models.Model):
organizer = models.CharField(max_length=100)
celebration_date = models.DateField()
budget = models.DecimalField(max_digits=10, decimal_places=2)
class Participant(models.Model):
draw = models.ForeignKey(Draw, related_name='participants', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
email = models.EmailField()
class Meta:
unique_together = ['draw', 'email']
And the following form:
python
class SorteoForm(forms.ModelForm):
class Meta:
model = Sorteo
fields = ['organizador', 'fecha_celebracion', 'presupuesto']
class ParticipanteForm(forms.ModelForm):
class Meta:
model = Participante
fields = ['nombre', 'email']
ParticipanteFormSet = formset_factory(ParticipanteForm)
To handle all this, I’m using the following view:
python
def create_draw(request):
if request.method == 'POST':
draw_form = DrawForm(request.POST)
if draw_form.is_valid():
draw = draw_form.save()
participant = ParticipantForm(request.POST)
if participant.is_valid():
participant.draw = draw.id
participant.save()
return render(request, 'draw_created.html')
else:
context = {
'draw_form': DrawForm(),
'participant_form': ParticipantForm(),
}
return render(request, 'create_draw.html', context)
Right now, all I need is to save the draw data along with the participants’ data in the database, so I can later implement the draw logic. I’ve managed to save one draw with one participant using the following template, where after a while, I managed to duplicate the participant form with a button:
html
<form action="" method="post">
{% csrf_token %}
{{ draw_form }}
<div id="participants" style="border: 1px solid; margin: 20px;">
{{ participant_form }}
{{ participant_form }}
{{ participant_form }}
</div>
<input type="submit" value="Create draw">
<button type="button" onclick="addParticipant()">Add participant</button>
</form>
<script type="text/javascript">
function addParticipant(){
var divParticipants = document.getElementById("participants")
divParticipants.innerHTML = divParticipants.innerHTML + `{{ participant_form }}`
console.log(divParticipants)
}
</script>
My problem arises when saving the data received in the view method. Only one participant is saved, even though at least three are always added in the template.