Comments (4)
@vitalik Could reproduce with this minimal setup (taken out and reduced from actual project)
from typing import Annotated, Literal
from ninja import Schema
from pydantic import ConfigDict
from ninja import Field
from pydantic import RootModel
class ExtraForbidSchema(Schema):
model_config = ConfigDict(extra="forbid")
class AbstractProfileIn(ExtraForbidSchema):
first_name: str | None = None
last_name: str | None = None
class NewUserBOIn(ExtraForbidSchema): # <==== If Schema it's good
email: str
role: str
project_id: int | None = None
class AdminProfileIn(AbstractProfileIn):
first_name: str
last_name: str
class AdminBOIn(NewUserBOIn):
site_ids: list[int] | None = Field(None, json_schema_extra={"deprecated": True})
role: Literal["ADMIN"]
profile: AdminProfileIn
class HCProfileIn(AbstractProfileIn):
first_name: str
last_name: str
class HCPBOIn(NewUserBOIn):
role: Literal["HCP"]
project_id: int
profile: HCProfileIn
class NewUserBOUnionIn(Schema, RootModel):
"""
Class to discriminate between different user roles with payload
The solution : https://github.com/pydantic/pydantic/issues/3714#issuecomment-1051093100
"""
root: Annotated[
(HCPBOIn | AdminBOIn),
Field(discriminator="role"),
]
def __getattr__(self, attr):
return getattr(self.root, attr)
def __getitem__(self, item):
return self.root[item]
user_data = {
"email": "[email protected]",
"project_id": "2",
"role": "HCP",
"profile": {"first_name": "FOO", "last_name": "BAR"}
}
user = NewUserBOUnionIn(**user_data)
print(user.email)
Full traceback :
Traceback (most recent call last):
File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/ninja/schema.py", line 66, in __getattr__
value = getattr(self._obj, key)
^^^^^^^^^^^^^^^^^^^^^^^
File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/ninja/schema.py", line 62, in __getattr__
raise AttributeError(key)
AttributeError: __dict__. Did you mean: '__dir__'?
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/django/template/base.py", line 821, in __init__
self.literal = int(var)
^^^^^^^^
ValueError: invalid literal for int() with base 10: '__dict__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/django/template/base.py", line 832, in __init__
self.literal = mark_safe(unescape_string_literal(var))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/django/utils/functional.py", line 246, in wrapper
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/django/utils/text.py", line 482, in unescape_string_literal
raise ValueError("Not a string literal: %r" % s)
ValueError: Not a string literal: '__dict__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/ninja/schema.py", line 70, in __getattr__
value = Variable(key).resolve(self._obj)
^^^^^^^^^^^^^
File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/django/template/base.py", line 837, in __init__
raise TemplateSyntaxError(
django.template.exceptions.TemplateSyntaxError: Variables and attributes may not begin with underscores: '__dict__'
thread '<unnamed>' panicked at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/pyo3-0.21.1/src/err/mod.rs:1098:5:
Python API call failed
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
--- PyO3 is resuming a panic after fetching a PanicException from Python. ---
Python stack trace below:
Traceback (most recent call last):
File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/ninja/schema.py", line 215, in _run_root_validator
return handler(values)
^^^^^^^^^^^^^^^
pyo3_runtime.PanicException: Python API call failed
--- PyO3 is resuming a panic after fetching a PanicException from Python. ---
Python stack trace below:
Traceback (most recent call last):
File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/ninja/schema.py", line 215, in _run_root_validator
return handler(values)
^^^^^^^^^^^^^^^
pyo3_runtime.PanicException: Python API call failed
Traceback (most recent call last):
File "/home/m3te0r/PycharmProjects/bepatient-server/ff.py", line 70, in <module>
user = NewUserBOUnionIn(**user_data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/pydantic/root_model.py", line 71, in __init__
self.__pydantic_validator__.validate_python(root, self_instance=self)
pyo3_runtime.PanicException: Python API call failed
I use combination of discriminated annotated unions schema + RootModel + Nested schemas with ConfigDict(extra="forbid")
If I remove the extra forbid from NewUserBOIn schema it works
from django-ninja.
Hi @M3te0r
Please check if latest pydantic (2.7.1) works for you
from django-ninja.
Hi @M3te0r
Maybe you have specific data that you pass to validation that is failing ? Please share you Schema class and data that you are passing
the latest full test run uses pydantic2.7 did not fail at any combination - https://github.com/vitalik/django-ninja/actions/runs/8661076227
from django-ninja.
Hi @vitalik
Minimal test code and actual project seems to work with pydantic v2.7.1 now
Many thanks !
from django-ninja.
Related Issues (20)
- [BUG] cdn error. HOT 3
- [BUG] paginate decorator with custom HTTP status `response={200: ..., 201: ...}` doesn't work HOT 3
- [BUG] Bearer authentication example from documentation doesn't work HOT 1
- `get_openapi_schema` outputs types using `anyOf` style - doesn't work with the Swift OpenAPI generator
- Error when trying to do django runserver -> pydantic.errors.PydanticSchemaGenerationError HOT 1
- [BUG] Using `pydantic.Json[SomeModel]` in a query param fails
- [BUG] Async Error Handlers Return Unawaited Coroutines Instead of HttpResponse in Django Ninja
- Dependency Injection support with `anydi`
- [BUG] `models.URLField` serialized & validated as `str` HOT 1
- Exceptions log level HOT 1
- [BUG] CustomParser request header issue when sending json and file
- [BUG] `ModelSchema` produces `id > (integer | null)` openapi HOT 1
- How to set query param for test.
- When are we getting a new release? HOT 2
- How to detect client disconnects on StreamingHttpResponse (Server Side Events)? HOT 4
- Support "Accept" & "Content-Type" Headers
- [BUG] no Response object generated for ASGI api route HOT 1
- Change settings access to support FastAPI-style single file apps
- How to test api.exception_handler
- Not required fields in FilterSchema
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from django-ninja.