Skip to content

DjangoUnicodeDecodeError for binary fields #700

@HealperRasmus

Description

@HealperRasmus

Issue Description

The smart_str() function fails when handling binary fields, raising:
django.utils.encoding.DjangoUnicodeDecodeError: 'utf-8' codec can't decode byte 0xaf in position 2: invalid start byte

Steps to Reproduce

  1. Create a model with a BinaryField
  2. Enable audit logging for this model
  3. Attempt to save/update the model with binary data

Current Behavior

Function fails with UnicodeDecodeError when trying to decode binary data as UTF-8

Expected Behavior

Binary data should be handled gracefully, possibly by converting to hex representation

Proposed Fix

The error occurs in the "smart_str" function. Adding a try catch with hex fallback could be a solution, but I cannot predict if that would have any unforeseen consequences?

def smart_str(s, encoding="utf-8", strings_only=False, errors="strict"):
    if isinstance(s, Promise):
        return s
    if isinstance(s, bytes):
        try:
            return force_str(s, encoding, strings_only, errors)
        except UnicodeDecodeError:
            return s.hex()
    return force_str(s, encoding, strings_only, errors)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions