Skip to content

Conversation

CarrotManMatt
Copy link
Contributor

I have made things!

The documentation for the method BaseForm.add_error() says the following:

The error argument can be a single error, a list of errors, or a
dictionary that maps field names to lists of errors. An "error" can be
either a simple string or an instance of ValidationError with its
message attribute set and a "list or dictionary" can be an actual
list or dict or an instance of ValidationError with its
error_list or error_dict attribute set.

If error is a dictionary, the field argument must be None and
errors will be added to the fields that correspond to the keys of the
dictionary.

I have updated the stubs for this method to include the additional types of errors as a list or dict. And made sure that the dict type can only be passed when field is None

@UnknownPlatypus
Copy link
Contributor

Would be nice to have a test in tests/assert_type showcasing what we should accept and what should be refused ?

You can take inspiration from tests/assert_type/http/test_request.py and run mypy --strict tests/assert_type && pyright tests/assert_type/ -p pyrightconfig.testcases.json from the root to check if everything pass (or the CI will do it)

Copy link
Member

@sobolevn sobolevn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, let's add a test :)

@CarrotManMatt
Copy link
Contributor Author

CarrotManMatt commented Aug 22, 2025

Due to the current implementation of ValidationError, the type system cannot inspect whether an instance's error_dict attribute is set and only allow the first overload signature of BaseForm.add_error() (with field required to be None).

I am also unaware of how to make these tests exhaustive by testing for the correct failing cases of field not set to None but error being a dictionary. Is there a assert_fails() equivalent to assert_type()?

@UnknownPlatypus
Copy link
Contributor

Is there a assert_fails() equivalent to assert_type()?

Not to my knowledge, but I believe the recommanded way to handle this is just to add appropriate type-ignore comments on offending lines

@CarrotManMatt
Copy link
Contributor Author

Cheers for the suggestion @UnknownPlatypus! I have now added these failure cases (still unable to test the introspection of a ValidationError instance's error_dict). So this PR is now complete from my side and ready for review.

Copy link
Member

@sobolevn sobolevn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@sobolevn sobolevn merged commit 71dd24a into typeddjango:master Aug 22, 2025
37 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

3 participants