Review a generated profile endpoint

from Django
Django 6.0.8 / Python 3.14 advanced 10 min 4 issues to find

Review this generated profile endpoint before it is deployed.

Let an authenticated user update only their own display name and time zone, reject malformed input, record an audit event atomically, and return the public profile.

Python
import json

from django.contrib.auth.decorators import login_required
from django.forms.models import model_to_dict
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
@login_required
def update_profile(request, account_id):
    payload = json.loads(request.body)
    account = Account.objects.get(pk=account_id)
    for field, value in payload.items():
        setattr(account, field, value)
    account.save()
    AuditEvent.objects.create(account=account, kind="profile.updated")
    active_sessions = len(list(account.sessions.all()))
    return JsonResponse(
        {"profile": model_to_dict(account), "active_sessions": active_sessions}
    )

generated code is illustrative, not from any one model

Open in playground
Report an error