Implemented editing for model instances

This commit is contained in:
2021-11-09 20:31:19 -06:00
parent 82c42e66ae
commit fa9a51509a
11 changed files with 84 additions and 21 deletions

View File

@@ -13,17 +13,22 @@ def list(request):
'items': [(player.id, f"{player.first_name} {player.last_name}") for player in players],
'edit_url_name': 'edit player'})
def edit(request, id=None):
def edit(request, id=0):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = PlayerForm(request.POST)
if id:
instance = get_object_or_404(Player, id=id)
form = PlayerForm(request.POST or None, instance=instance)
else:
form = PlayerForm(request.POST or None)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponse(str(form.cleaned_data))
new_player, did_create = Player.objects.update_or_create(pk=id, defaults=form.cleaned_data)
return render(request, 'success.html', {'call_back':'players list'})
# if a GET (or any other method) we'll create a blank form
else:
@@ -33,4 +38,4 @@ def edit(request, id=None):
else:
form = PlayerForm
return render(request, 'players/edit.html', {'form': form, 'id': id})
return render(request, 'edit.html', {'form': form, 'id': id, 'call_back':'edit player'})