Skip to content

Commit

Permalink
v1
Browse files Browse the repository at this point in the history
  • Loading branch information
vitalik committed Jul 7, 2023
2 parents 1c4ec55 + 77e38ca commit 8c422ac
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 18 deletions.
21 changes: 8 additions & 13 deletions docs/src/tutorial/form/code03.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,17 @@
from ninja import Form, Schema
from pydantic import FieldValidationInfo
from typing import Annotated, TypeVar
from pydantic import WrapValidator
from pydantic_core import PydanticUseDefault
from pydantic_core import core_schema
from typing import Any, Generic, TypeVar

PydanticField = TypeVar("PydanticField")

def _empty_str_to_default(v, handler, info):
if isinstance(v, str) and v == '':
raise PydanticUseDefault
return handler(v)

class EmptyStrToDefault(Generic[PydanticField]):
@classmethod
def __get_pydantic_core_schema__(cls, source, handler):
return core_schema.field_plain_validator_function(cls.validate)

@classmethod
def validate(cls, value: Any, info: FieldValidationInfo) -> Any:
if value == "":
raise PydanticUseDefault()
return value
T = TypeVar('T')
EmptyStrToDefault = Annotated[T, WrapValidator(_empty_str_to_default)]


class Item(Schema):
Expand Down
1 change: 1 addition & 0 deletions ninja/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

__version__ = "1.0a1"


from pydantic import Field

from ninja.files import UploadedFile
Expand Down
9 changes: 4 additions & 5 deletions ninja/orm/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

from django.db.models import ManyToManyField
from django.db.models.fields import Field as DjangoField
from django.utils.functional import keep_lazy_text
from pydantic import IPvAnyAddress
from pydantic.fields import FieldInfo
from pydantic_core import PydanticUndefined, core_schema
Expand All @@ -16,7 +15,9 @@
__all__ = ["create_m2m_link_type", "get_schema_field", "get_related_field_schema"]


@keep_lazy_text
# keep_lazy seems not needed as .title forces translation anyway
# https://github.com/vitalik/django-ninja/issues/774
# @keep_lazy_text
def title_if_lower(s: str) -> str:
if s == s.lower():
return s.title()
Expand Down Expand Up @@ -102,9 +103,7 @@ def _validate(cls, v: Any, _):


@no_type_check
def get_schema_field(
field: DjangoField, *, depth: int = 0, optional: bool = False
) -> Tuple:
def get_schema_field(field: DjangoField, *, depth: int = 0, optional: bool = False) -> Tuple:
"Returns pydantic field from django's model field"
alias = None
default = ...
Expand Down

0 comments on commit 8c422ac

Please sign in to comment.