Fix Mass Assignment in Django
Mass Assignment in Django happens when you blindly trust user-supplied dictionaries to update model instances. Attackers can inject unexpected keys (e.g., 'is_admin', 'balance') into the request payload to escalate privileges or modify restricted internal state. If you are unpacking **request.POST or **request.data directly into a model constructor or .update() call, your app is pwned.
The Vulnerable Pattern
def update_profile(request):
# VULNERABLE: Direct attribute injection via request.POST
# An attacker sends 'bio=testing&is_staff=True' to gain admin access
user = request.user
for key, value in request.POST.items():
setattr(user, key, value)
user.save()
return HttpResponse('Profile updated')
The Secure Implementation
The vulnerability stems from the 'Implicit Trust' anti-pattern. The fix is strict Allow-listing. By using a Django ModelForm with a defined 'fields' attribute, we create a whitelist that ignores any extra keys injected into the POST body. Even if an attacker sends 'is_staff=True', the form processor will ignore it because it is not defined in the Meta class. If you are using Django REST Framework (DRF), achieve the same security by explicitly defining 'fields' in your Serializer and avoiding the use of '__all__'.
from django import formsclass UserProfileForm(forms.ModelForm): class Meta: model = User # SECURE: Explicitly allow-list only the fields the user is allowed to touch fields = [‘bio’, ‘location’, ‘website’]
def update_profile(request): form = UserProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return HttpResponse(‘Profile updated’) return HttpResponseBadRequest(‘Invalid data’)
Your Django API
might be exposed to Mass Assignment
74% of Django apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.