typeddjango / django-stubs

PEP-484 stubs for Django
MIT License
1.59k stars 444 forks source link

Infer type for Form.fields #1514

Open andraantariksa opened 1 year ago

andraantariksa commented 1 year ago

https://stackoverflow.com/questions/73600700/best-practice-for-python-typing-out-of-dictionary-self-fields-type-in-django-mo

I'm looking to infer dictionary values type for this snippet

class MerchantBrandsForm(forms.Form):
    brands = forms.ModelChoiceField(required=True, queryset=None)

    def __init__(self: merchant: Merchant, *args: Any, **kwargs: Any):
        super().__init__(*args, **kwargs)
        self.fields['brands'].queryset = merchant.brands.all()
           # ^^^^^^^^^^
           # This would be a type error since forms.ModelChoiceField is generalized to forms.Field

self.fields type above should be inferred to

class Fields(TypedDict):
    brands: forms.ModelChoiceField
sobolevn commented 1 year ago

This needs a plugin similar to one we have for models. If you want to work on this, I can provide all the help you need :)

andraantariksa commented 1 year ago

This needs a plugin similar to one we have for models. If you want to work on this, I can provide all the help you need :)

Sure, I can work on this. Please give me some pointers

asottile-sentry commented 6 months ago

I'm going to close my duplicate of this since it's probably better tacked here: #1208