def update(request, id):/update/番号 でアクセスした時の番号が、そのままidというパラメータとして渡されるようになっています。これをもとに、指定のID番号のPersonを変数currentに取り出しておきます。
current = Person.objects.get(id=id)objects.getは、既に説明しましたね。これで指定のIDのレコードをPersonインスタンスとして用意できました。後は、送信されたフォームの値を使ってインスタンスのプロパティを更新し、保存するだけです。
current.name = request.POST['name']既にあるレコードを更新する場合も、新規保存と同じ「save」を使います。これで、更新されたレコードが保存できました!
current.mail = request.POST['mail']
current.age = request.POST['age']
current.save()
return redirect('index')redirectは、リダイレクトのHttpResponseを返すショートカット関数です。このredirect関数の戻り値をそのままreturnすることで、リダイレクトを実行できます。redirect関数の引数には、リダイレクト先を指定します。
from django.shortcuts import redirect
※リストが表示されない場合
AddBlockなどの広告ブロックツールがONになっているとリストなどが表示されない場合があります。これらのツールをOFFにしてみてください。
from django.shortcuts import redirect #追加 def update(request, id): current = Person.objects.get(id=id) if request.method == 'POST': current.name = request.POST['name'] current.mail = request.POST['mail'] current.age = request.POST['age'] current.save() return redirect('index') context = { 'current': current, 'msg': 'Person ID=' + str(id) + 'の更新', } return render(request, 'hello/update.html', context)
<< 前へ | 次へ >> |