Djangoプレミアム--フォームデータの提出と受信

9302 ワード

フォームデータのコミットと受信
本番組表
  • フォーム作成
  • GetとPostのリクエスト方式
  • 明後日データ取得
  • フォーム作成
    フォームラベルformの作成の復習
    formタグコミットアドレスactionコミットメソッドmethod get postコミットファイルenctype=「multipart/form-data」例:
    inputラベルの復習
    Input type="text"テキスト入力ボックスtype="password"パスワード入力ボックスtype="radio"ラジオボックスtype="checkbox"チェックボックスtype="file"ファイルボックスtype="button"ボタンtype="submit"コミットtype="reset"リセット
    例:
    ドロップダウン・ボックスと大きなテキスト・ボックスのラベルの復習
    ドロップダウン:オプション1オプション2テキスト:
    GetとPostリクエスト
    getがコミットしたデータパラメータはurlでpostがコミットしたデータが暗号化され、urlにはget要求のurlフォーマットターゲットサイト:www.eduが見えない.csdn.Netコミットパラメータ:name=123 pass=456 www.edu.csdn.net/?name=123&pass=456
    バックグラウンドデータの取得
    Getリクエスト:value=request.GET.get(【key】,【デフォルト】)values=request.GET.getlist(【key】)Postリクエスト:value=request.POST.get(【key】,【デフォルト】)values=request.POST.getlist(【key】)注:Postリクエストは、フォームに{%csrf_token%}を追加するか、csrfミドルウェアをキャンセルする必要があります.
  • 機能ルーティングの追加
  •     path('form',views.form_handler,name = 'form'),
        path('form_get',views.form_get_handler,name ='form_get'),
        path('form_post',views.form_post_handler,name = 'form_post')
    ]
    
  • ビュー関数の作成
  • def form_handler(request):
        return render(request,'form.html')
    
    
    def form_get_handler(request):
        username = request.GET.get('username')
        hobbys = request.GET.getlist('hobby')
        print('username:',username)
        print('hobbys:',hobbys)
        return HttpResponse('')
    
    
    
    def form_post_handler(request):
        username = request.POST.get('username')
        hobbys = request.POST.getlist('hobby')
        print('username:',username)
        print('hobbys:',hobbys)
        return HttpResponse('')
    
  • HTMLページの作成
  • <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <form action="{% url 'form_post' %}" method="post">
        {
         % csrf_token %}
        username:
        <input type="text" name="username"><br/>
        hobby:
        <input type="checkbox" name="hobby" value="Python">Python
        <input type="checkbox" name="hobby" value="Java">Java
        <br/>
        <input type="submit" value="Submit">
    </form>
    </body>
    </html>