Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix no URL validation for ModelSchema URLFields #1255

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 30 additions & 3 deletions ninja/orm/fields.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import datetime
from decimal import Decimal
from typing import Any, Callable, Dict, List, Tuple, Type, TypeVar, Union, no_type_check
from typing import Annotated, Any, Callable, Dict, List, Tuple, Type, TypeVar, Union, no_type_check
from uuid import UUID

from django.db.models import ManyToManyField
from django.db.models import ManyToManyField, URLField
from django.db.models.fields import Field as DjangoField
from pydantic import IPvAnyAddress
from pydantic import AnyUrl, IPvAnyAddress, TypeAdapter
from pydantic.fields import FieldInfo
from pydantic_core import PydanticUndefined, core_schema

Expand Down Expand Up @@ -42,6 +42,29 @@ def validate(cls, value: Any, _: Any) -> Any:
return value


# Allows to have url validation on URLFields without breaking JSON serialization
# https://github.com/vitalik/django-ninja/pull/1255
class AnyUrlStr(str):
@classmethod
def __get_pydantic_core_schema__(
cls, source: Any, handler: Callable[..., Any]
) -> Any:
return core_schema.with_info_plain_validator_function(cls.validate)

@classmethod
def __get_pydantic_json_schema__(
cls, schema: Any, handler: Callable[..., Any]
) -> DictStrAny:
return {"type": "string"}

@classmethod
def validate(cls, value: Any, _: Any) -> str:
if isinstance(value, AnyUrl):
return str(value)
validated = TypeAdapter(AnyUrl).validate_python(value)
return str(validated)


TYPES = {
"AutoField": int,
"BigAutoField": int,
Expand Down Expand Up @@ -69,6 +92,7 @@ def validate(cls, value: Any, _: Any) -> Any:
"SmallIntegerField": int,
"TextField": str,
"TimeField": datetime.time,
"URLField": AnyUrlStr,
"UUIDField": UUID,
# postgres fields:
"ArrayField": List,
Expand Down Expand Up @@ -148,6 +172,9 @@ def get_schema_field(
max_length = field_options.get("max_length")

internal_type = field.get_internal_type()
if isinstance(field, URLField):
internal_type = "URLField"

python_type = TYPES[internal_type]

if field.primary_key or blank or null or optional:
Expand Down
Loading