0

I want to use django.views.generic.edit.FormView and since it's a generic, I'm giving it a type argument (MyForm):

class MyView(FormView[MyForm]):
    ...

But it causes this error:

TypeError: 'type' object is not subscriptable

What's the proper way to pass type arguments to FormView?

1 Answer 1

1

You have two options (or three, if you include ignoring the error in mypy)

Monkeypatching

Monkeypatch the classes at runtime by putting

import django_stubs_ext

django_stubs_ext.monkeypatch()

in your <mysite>/settings.py file

https://github.com/typeddjango/django-stubs#i-cannot-use-queryset-or-manager-with-type-annotations

TypeAlias behind TYPE_CHECKING guard

if typing.TYPE_CHECKING:
  MyFormView = FormView[MyForm]
else:
  MyFormView = FormView

class MyView(MyFormView)):
  ...

this means you don't need django-stubs-ext as a runtime dependency.

Sign up to request clarification or add additional context in comments.

1 Comment

I used the second approach: "TypeAlias behind TYPE_CHECKING guard" and it worked! thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.