def METHOD_NAME(request, user_pk):
    """
    Add a hat to a user.
    Creates the hat if it doesn't exist.
    """
    user = get_object_or_404(User, pk=user_pk)
    hat_name = request.POST.get("hat", "")
    try:
        hat = get_hat_to_add(hat_name, user)
        user.profile.hats.add(hat)
        try:  # if hat was requested, remove the relevant request
            hat_request = HatRequest.objects.get(user=user, hat__iexact=hat.name, is_granted__isnull=True)
            hat_request.solve(
                is_granted=False,
                comment=_(
                    "La demande a été automatiquement annulée car " "la casquette vous a été accordée manuellement."
                ),
            )
        except HatRequest.DoesNotExist:
            pass
        messages.success(request, _("La casquette a bien été ajoutée."))
    except ValueError as e:
        messages.error(request, str(e))
    return redirect(user.profile.get_absolute_url())