私は自分の見解でこのことをかなり頻繁に使用していますが、それが正確に何を意味するのか知りたいです。
orと書くとどうなりますrequest.method == "GET"
かrequest.method == "POST"
?
の結果request.method == "POST"
はブール値です -True
ユーザーからの現在のリクエストが HTTP "POST" メソッドを使用して実行された場合、それ以外のFalse
場合 (通常は HTTP "GET" を意味しますが、他のメソッドもあります)。
GET と POST の違いについて詳しくは、Alasadir が指摘した質問への回答を参照してください。簡単に言えば、POST リクエストは通常、フォームの送信に使用されます。フォームの処理によってサーバー側の状態が変わる場合に必要です (たとえば、登録フォームの場合、データベースにユーザーを追加するなど)。GET は、通常の HTTP リクエスト (たとえば、ブラウザに URL を入力するだけの場合) と、副作用なしで処理できるフォーム (たとえば、検索フォーム) に使用されます。
コードは通常、送信されたフォームを処理するためのコードとバインドされていないフォームを表示するためのコードを区別するために、条件ステートメントで使用されます。
if request.method == "POST":
# HTTP Method POST. That means the form was submitted by a user
# and we can find her filled out answers using the request.POST QueryDict
else:
# Normal GET Request (most likely).
# We should probably display the form, so it can be filled
# out by the user and submitted.
そして、Django Forms ライブラリを使用して、Django documentation から直接取得した別の例を次に示します。
from django.shortcuts import render
from django.http import HttpResponseRedirect
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render(request, 'contact.html', {
'form': form,
})