Skip to main content
 首页 » 编程设计

python之使用 render_to_string 时填充 {% csrf_token %}

2025年05月04日17lyj

我需要使用render_to_string,但是我不能使用

@csrf_protect 

并通过

context_instance=RequestContext(request))  

到 render_to_string,因为我认为装饰器期待的是 HttpResponse,而不是 SafeString。

如何将 csrf_token 放入我的字符串中?

'NoneType' object has no attribute 'COOKIES'

编辑:感谢您的评论,这里有一些澄清:

我正在创建一个“面板”系统,类似于“portlets”,其中面板在数据库中配置(包括将面板呈现为字符串的 python 函数的名称 - 面板函数在运行时从它们的导入数据库中的名称)。

为了将这些面板放入页面中,我创建了一个自定义模板标签,它从数据库中读取所需面板的名称,将它们呈现为字符串,然后返回一大块 html(作为字符串)到正在呈现的页面。 (这允许用户选择为他们显示哪些面板。)

我的问题是其中一个面板(使用 render_to_string 将模板呈现为字符串的简单 python 函数)中有一个表单。

我需要将 CSRF 字段插入该表单,因为它被呈现为字符串。

请您参考如下方法:

我已经解决了这个问题,但我仍然非常想要一个好的解决方案。

面板功能现在看起来像:

def render_to_s(request, *args, **kwargs): 
    panelDisplays = PanelDisplay.listAll() 
    csrf_token_value = request.COOKIES['csrftoken'] 
 
    c = {"panelDisplays": panelDisplays, "csrf_token_value": csrf_token_value} 
    return render_to_string('panels/config.html', c) 

虽然模板现在包括:

<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='{{ csrf_token_value }}'/></div>