Hi all!

Currently django views do not accept dataclasses as context.

I stumbled about this because I wanted to do something like this:

@cached_property
def extra_context(self):
    data = MyDataClass(...)
    ...
    return data

Unfortunately, this is unpacked by get_context_data and throws an error 
because a dataclass can't be iterated (core code):


def get_context_data(self, **kwargs):
    kwargs.setdefault('view', self)
    if self.extra_context is not None:
        kwargs.update(self.extra_context)
    return kwargs


I know I could do a asdict(data)inside the `extra_context` but with the 
transformation to a dict, I will lose all my typesafety, e.g.:


def get_template_names(self):
    if self.extra_context.somedata:  # << somedata is typed
        ...

A simple check for dataclass would be nice (
https://docs.python.org/3/library/dataclasses.html#dataclasses.is_dataclass
):


def get_context_data(self, **kwargs):
    kwargs.setdefault('view', self)
    if self.extra_context is not None:
        if is_dataclass(self.extra_context) and not 
isinstance(self.extra_context, type):
            kwargs.update(asdict(self.extra_context))
        else:
            kwargs.update(self.extra_context)
    return kwargs


Kind regards!

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/b43c5655-c44a-4f9b-8503-37366ec7ea5en%40googlegroups.com.
  • [Fe... Arthur
    • ... 'Adam Johnson' via Django developers (Contributions to Django itself)

Reply via email to