Skip to content

Typing error in CountryField #482

@patrykgawinek

Description

@patrykgawinek

The CountryField field supports setting a custom countries class through a countries parameter. I use this to limit the countries on a specific model like the following example:

class LimitedCountries(Countries): ...

class SomeModel(models.Model):
    country = CountryField(countries=LimitedCountries)

This worked fine until the 8.0.1 -> 8.1.0 update, and should still be supported. I have not experienced runtime issues, just typing errors.
The issue was introduced through the addition of a stub file here.

Expected Behavior

CountryField accepts Type[Countries] in its countries argument, to allow Countries customization.

Current Behavior

Mypy raises issues regarding no overloads matching the defined types.

demo_app\models.py:10: error: No overload variant of "CountryField" matches argument type "type[CustomCountries]"  [call-overload]
demo_app\models.py:10: note: Possible overload variants:
demo_app\models.py:10: note:     def CountryField(self, *, multiple: Literal[False] = ..., null: Literal[False] = ..., blank: bool = ..., countries: Countries | None = ..., countries_flag_url: str | None = ..., countries_str_attr: str = ..., blank_label: str | None = ..., **kwargs: Any) -> CountryField
...

Possible Solution

Overloads for CountryField in fields.pyi should define the countries argument and property as Type[Countries], rather than Countries.

Steps to Reproduce

  1. Create a new country class, inheriting from Countries.
  2. Create a new model with a CountryField.
  3. Set countries keyword argument to new Country class
  4. Run mypy
from django.db import models
from django_countries.fields import CountryField
from django_countries import Countries


class CustomCountries(Countries): ...


class ExampleModel(models.Model):
    country = CountryField(countries=CustomCountries)

This is also covered by the current codebase. Running the following command should trigger the typing error:
mypy .\django_countries\tests\models.py

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions