Django 1.11 TypeError context must be a dict rather than Context

后端 未结 3 1316
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 15:33

Just received the Sentry error TypeError context must be a dict rather than Context. on one of my forms. I know it has something to do with Django 1.11, but I

相关标签:
3条回答
  • 2020-12-01 15:58

    Migrated from Django 1.8 to Django 1.11.6

    Wherever i had a RequestContext class, there is a method flatten() wich return the result as a dict.

    So if the class is RequestContext....

    return t.render(context)
    

    becomes

    return t.render(context.flatten())
    

    And in a case wich the context is is wrapped by Context(), just remove it. Because Context() is deprecated.

    return t.render(Context(ctx))
    

    becomes

    return t.render(ctx)
    
    0 讨论(0)
  • 2020-12-01 16:03

    For django 1.11 and after, context must be dict.

    You can use:

    context_dict = get_context_dict(context)
    return t.render(context_dict)
    

    or

    context_dict = context.flatten()
    return t.render(context_dict)
    
    0 讨论(0)
  • 2020-12-01 16:12

    In Django 1.8+, the template's render method takes a dictionary for the context parameter. Support for passing a Context instance is deprecated, and gives an error in Django 1.10+.

    In your case, just use a regular dict instead of a Context instance:

    message = get_template('email_forms/direct_donation_form_email.html').render(ctx)
    

    You may prefer to use the render_to_string shortcut:

    from django.template.loader import render_to_string
    
    message = render_to_string('email_forms/direct_donation_form_email.html', ctx)
    

    If you were using RequestContext instead of Context, then you would pass the request to these methods as well so that the context processors run.

    message = get_template('email_forms/direct_donation_form_email.html').render(ctx, request=request)
    message = render_to_string('email_forms/direct_donation_form_email.html', ctx, request=request)
    
    0 讨论(0)
提交回复
热议问题