タイトル: django.utils.datastructures.MultiValueDictKeyError
SEOタイトル: Django「MultiValueDictKeyError」原因と対処|request.POST の安全な取得
この本文には実行可能なタグ等が含まれるため、安全のためHTMLソースとして表示しています。本文データは変更していません。
<table border="1" cellpadding="6" cellspacing="0" style="border-collapse:collapse;background:#fffbea;border:1px solid #f4c430;margin:1em 0;width:100%"><tr><td style="background:#f4c430;color:#000;font-weight:bold;padding:8px">この記事の要点</td></tr><tr><td style="padding:10px"><ul><li>Django の <strong>MultiValueDictKeyError</strong></li><li>原因: <code>request.POST["key"]</code> 等で<strong>存在しないキーを直接アクセス</strong>している</li><li>対処: <strong><code>request.POST.get("key", デフォルト値)</code></strong> を使う</li><li>または <code>if "key" in request.POST</code> で事前チェック</li><li>フォームクラスを使えば <code>form.cleaned_data</code> 経由でバリデーション込みで安全</li></ul></td></tr></table>
<h2>エラー内容</h2>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-text">django.utils.datastructures.MultiValueDictKeyError: 'username'
Internal Server Error: /login
Traceback (most recent call last):
...
File "/path/to/views.py", line 25, in login_view
username = request.POST['username']
File ".../django/utils/datastructures.py", line nnn, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'username'</code></pre>
<h2>原因</h2>
<p>Django の <code>request.POST</code> / <code>request.GET</code> は <code>MultiValueDict</code> という辞書ライクなオブジェクトです。Python の通常の dict と同じく <code>['key']</code> でアクセスすると、<strong>キーが存在しない場合に例外</strong>を投げます。</p>
<p>典型例:</p>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-python"># views.py
def login_view(request):
if request.method == 'POST':
# ❌ NG: 必須項目が送信されていない場合に例外
username = request.POST['username']
password = request.POST['password']
# ...
return render(request, 'login.html')</code></pre>
<p>フォームが正しく送信されればキーは存在しますが、以下のケースで存在しなくなります:</p>
<ul>
<li>HTML フォームの <code>name="username"</code> 属性が無い・タイポ</li>
<li>JavaScript で fetch / axios 直叩きしたときにパラメータ欠落</li>
<li>API テストツール (Postman / curl) で必須項目を忘れる</li>
<li>悪意のあるリクエスト(フォーム外からのアクセス)</li>
</ul>
<h2>対処1: .get() を使う(最も簡単)</h2>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-python">def login_view(request):
if request.method == 'POST':
# ✅ OK: 存在しない場合は None
username = request.POST.get('username')
# ✅ OK: デフォルト値を指定
username = request.POST.get('username', '')
password = request.POST.get('password', '')
# 必須チェックを別途
if not username or not password:
return render(request, 'login.html', {
'error': 'ユーザー名とパスワードを入力してください'
})
# ... 認証処理
return render(request, 'login.html')</code></pre>
<h2>対処2: in 演算子で事前チェック</h2>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-python">def login_view(request):
if request.method == 'POST':
if 'username' in request.POST and 'password' in request.POST:
username = request.POST['username']
password = request.POST['password']
# ...
else:
return HttpResponseBadRequest('Missing required fields')
return render(request, 'login.html')</code></pre>
<h2>対処3: try/except で例外捕捉</h2>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-python">from django.utils.datastructures import MultiValueDictKeyError
def login_view(request):
if request.method == 'POST':
try:
username = request.POST['username']
password = request.POST['password']
except MultiValueDictKeyError as e:
return JsonResponse({'error': f'Missing: {e}'}, status=400)
# ...
return render(request, 'login.html')</code></pre>
<h2>対処4: Form クラスでバリデーション(推奨)</h2>
<p>Django Forms を使うのが正攻法。フィールド定義と必須チェック・型変換を一元化できます:</p>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-python"># forms.py
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(max_length=150)
password = forms.CharField(widget=forms.PasswordInput)
# views.py
from .forms import LoginForm
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
# ... 認証処理
else:
return render(request, 'login.html', {'form': form})
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})</code></pre>
<h2>対処5: DRF (Django REST Framework) Serializer</h2>
<p>API として作るなら DRF のシリアライザで:</p>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-python">from rest_framework import serializers, status
from rest_framework.response import Response
from rest_framework.decorators import api_view
class LoginSerializer(serializers.Serializer):
username = serializers.CharField(max_length=150)
password = serializers.CharField(write_only=True)
@api_view(['POST'])
def login_api(request):
serializer = LoginSerializer(data=request.data)
if serializer.is_valid():
username = serializer.validated_data['username']
password = serializer.validated_data['password']
# ... 認証処理
return Response({'success': True})
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)</code></pre>
<h2>MultiValueDict の特殊操作</h2>
<p>同じキーで複数の値が送られる場合(チェックボックスのリスト等)には専用メソッド:</p>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-python"># HTML: <input type="checkbox" name="tags" value="python">
# <input type="checkbox" name="tags" value="django">
# <input type="checkbox" name="tags" value="flask">
# 単一値(最後の値)
tag = request.POST['tags'] # → "flask"
# すべての値をリストで
tags = request.POST.getlist('tags') # → ['python', 'django', 'flask']
# 安全に取得(空リストがデフォルト)
tags = request.POST.getlist('tags', [])</code></pre>
<h2>HTML テンプレート側で要点を絞る</h2>
<p>そもそもフォームの <code>name</code> 属性が正しいか:</p>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-html"><!-- ❌ NG: name 属性が無い -->
<form method="POST">
{% csrf_token %}
<input type="text">
<input type="password">
<button type="submit">ログイン</button>
</form>
<!-- ✅ OK: name 属性必須 -->
<form method="POST" action="{% url 'login' %}">
{% csrf_token %}
<input type="text" name="username" required>
<input type="password" name="password" required>
<button type="submit">ログイン</button>
</form></code></pre>
<h2>関連エラー</h2>
<ul>
<li><strong>"403 Forbidden CSRF verification failed"</strong> — CSRF トークン不足 → <code>{% csrf_token %}</code> 追加</li>
<li><strong>"KeyError" (Django テンプレート側)</strong> — context dict に値が無い → <code>{% if var %}</code> でガード</li>
<li><strong>"AttributeError: 'NoneType' object has no attribute"</strong> — .get() で None が返って、その後で属性アクセスしている</li>
</ul>
<h2>Best Practice</h2>
<ol>
<li><strong>Form クラスを使う</strong> — 型変換・必須チェック・カスタムバリデーションが一元化</li>
<li><strong>直接 request.POST にアクセスしない</strong> — 例外が出る</li>
<li><strong>テスト</strong> — フィールド未送信のケースもテストケースに含める</li>
<li><strong>APIs は DRF</strong> — Serializer で同じ思想を REST API にも適用</li>
</ol>