clean an ipv6 address string raise validationerror if the address is invalid replace the longest continuous zerosequence with remove leading zeroes and make sure all hextets are lowercase args ipstr a valid ipv6 address unpackipv4 if an ipv4mapped address is found return the plain ipv4 address defaultfalse errormessage an error message used in the validationerror return a compressed ipv6 address or the same value return whether or not the ipstr string is a valid ipv6 address clean an ipv6 address string raise validationerror if the address is invalid replace the longest continuous zero sequence with remove leading zeroes and make sure all hextets are lowercase args ip_str a valid ipv6 address unpack_ipv4 if an ipv4 mapped address is found return the plain ipv4 address default false error_message an error message used in the validationerror return a compressed ipv6 address or the same value return whether or not the ip_str string is a valid ipv6 address
import ipaddress

from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _


def clean_ipv6_address(
    ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.")
):
    
    try:
        addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str)))
    except ValueError:
        raise ValidationError(
            error_message, code="invalid", params={"protocol": _("IPv6")}
        )

    if unpack_ipv4 and addr.ipv4_mapped:
        return str(addr.ipv4_mapped)
    elif addr.ipv4_mapped:
        return "::ffff:%s" % str(addr.ipv4_mapped)

    return str(addr)


def is_valid_ipv6_address(ip_str):
    
    try:
        ipaddress.IPv6Address(ip_str)
    except ValueError:
        return False
    return True