开发者

Why do I got "KeyError: template_name" when serializing a Django Response object?

开发者 https://www.devze.com 2023-03-15 08:51 出处:网络
The cache middleware must pickle the Response object but sometime when it does, it fails: [...]/.virtualenvs/project/lib/python2.7/site-packages/django/template/response.py in __getstate__

The cache middleware must pickle the Response object but sometime when it does, it fails:

[...]/.virtualenvs/project/lib/python2.7/site-packages/django/template/response.py in __getstate__

    Ensures that the object can't be pickled before it has been
    rendered, and that the pickled state only includes rendered
    data, not the data used to construct the response.
    """
    obj_dict = self.__dict__.copy()
    if not self._is_rendered:
    raise ContentNotRenderedError('The response content must be rendered before it can be pickled.')

    del obj_dict['template_name'] ...

    KeyError: template_name

The local vars are:

Variable  Value
self  

u'Content-Language: fr\nExpires: Thu, 23 Ju开发者_如何学Pythonn 2011 17:40:18 GMT\nVary: Accept-Language, Cookie\nLast-Modified: Thu, 23 Jun 2011 11:40:18 GMT\nCache-Control: max-age=21600\nContent-Type: text/html; charset=utf...'

obj_dict  

{'_charset': 'utf-8',
 '_container': [u'\n\n\n\n\n<li>\n    <a href="/video/42506/outdoor-demo">\n        <img src="http://str2.site.com/4/2/5/0/6/42506/screenshots_80x80/4.jpg" />\n        <h3>Outdoor demo </h3>\n        <p>\n            <st...'],
 '_headers': {'cache-control': ['Cache-Control', 'max-age=21600'],
              'content-language': ['Content-Language', 'fr'],
              'content-type': ['Content-Type', 'text/html; charset=utf-8'],
              'expires': ['Expires', 'Thu, 23 Jun 2011 17:40:18 GMT'],
              'last-modified': ['Last-Modified',
                                'Thu, 23 Jun 2011 11:40:18 GMT'],
              'vary': ['Vary', 'Accept-Language, Cookie']},
 '_is_rendered': True,
 '_is_string': True,
 'cookies': {}}
    del obj_dict['context_data']
    del obj_dict['_post_render_callbacks']
    return obj_dict
    def resolve_template(self, template):

The problem doesn't occur all the time, and I'm not sure, but I think it's related only to one type of view when it's called with AJAX. Here is an example view:

class CategoriesView(ChunkTemplateResponseMixin, generic.ListView):
    """
        List categories
    """
    template_name = 'app/categories.html'
    context_object_name = 'categories'
    paginate_by = 10
    model = Tag
    chunk_template_name = 'app/categories_chunk.html'
    chunk_marker = 'chunk'

    def get_queryset(self): 
        """
            Return the categ by usage, removing categs with no videos on the
            current site
        """

        categs = []
        videos = Video.on_site.all()
        for tag in Video.tags_set.usage():
            if Video.tagged.with_all(tag, videos).count() > 25:
                categs.append(tag)

        return categs

Here is apparently the common denominator to all the views failling:

class ChunkTemplateResponseMixin(TemplateResponseMixin):
    """
        Return a different template if the request pass a parameter.

        If all request are in ajax and you still want to differentiate
        page loaded entirely from chunk, set chunk marker to a string
        that enable the alternate template rendering when found in
        GET or POST.

        eg: /categories => normal template
            /categories?chunk=True => chunk template

    """

    chunk_marker = None
    chunk_template_name = None

    def is_chunk(self):
        """
            Check if the template chunk should be rendered instead of
            the original one.
        """

        if self.chunk_marker:
            return self.chunk_marker in self.request.REQUEST
        return self.request.is_ajax()


    def render_to_response(self, *args, **kwargs):

        if self.is_chunk():
            self.template_name = self.chunk_template_name

        return super(ChunkTemplateResponseMixin, 
                      self).render_to_response(*args, **kwargs)

I'm guessing there is something related to it's TemplateResponseMixin parent but I do set template_name on the child. enter code here

0

精彩评论

暂无评论...
验证码 换一张
取 消