A student wanted to create several tables with foreign keys linking them. He was placing the forms all over the place and that just didn't seem to make sense to me. I suggested that he link all the forms to one main registration page, and while he worked on it, I came up with my own solution that I feel rather proud of. Though I'm well aware it is a very simple solution.
views.py
def register(request):
# form for team
formteam = TeamForm(request.POST or None)
if formteam.is_valid():
formteam.save()
return redirect('registerForTeam')
else:
print(formteam.errors)
formteam = TeamForm()
# form for coach
formcoaches = CoachesForm(request.POST or None)
if formcoaches.is_valid():
formcoaches.save()
return redirect('registerForTeam')
else:
print(formcoaches.errors)
formcoaches = CoachesForm()
# form for player
formplayer = PlayersForm(request.POST or None)
if formplayer.is_valid():
formplayer.save()
return redirect('registerForTeam')
else:
print(formplayer.errors)
formplayer = PlayersForm()
context = {
'team': formteam,
'coach': formcoaches,
'player': formplayer
}
return render(request, 'SoccerApp/SoccerAppRegister.html', context)
I put all the forms in a single view function so that I can use modals to render the forms. I used Bootstrap to create the modals. I was stuck at this point for a shamefully long time, before I realised that Javascript was not added to the base template, and that was what was preventing me from rendering the modals. *facepalm* I'm not really pleased with the long view function and I'm sure there's probably a better way to do this. I'll look at it again at some point and try and figure it out. I haven't really tried using class based views and I wonder if that would make things more readable? I'm putting that on my to do list.
Comments
Post a Comment