【问题标题】:RequestContext with django-widgets so that CSRF worksRequestContext 与 django-widgets 以便 CSRF 工作
【发布时间】:2011-10-15 23:37:08
【问题描述】:

我在一个项目中使用http://code.google.com/p/django-widgets/,在我看来,我正在使用 AJAX 发送电子邮件,如下所示:

def contact_submit(request):
    form = ContactForm(data=request.POST)
    ajax = request.is_ajax()
    if form.is_valid():
        form.save();

        name = form.cleaned_data['name']
        phone = form.cleaned_data['phone']
        email = form.cleaned_data['email']
        company = form.cleaned_data['company']
        comment = form.cleaned_data['comments']
        send_email(name, company, phone, email, comment)

        if ajax:
            return HttpResponse('{"success":true}')
        else:
            return redirect( request.META['HTTP_REFERER'] )
    else:
        if ajax:
            return HttpResponse('{"success":false}')
        else:
            return redirect( request.META['HTTP_REFERER'] )

我的问题是我的模板中的 csrf_token 没有显示出来。我知道这是因为我的模板中没有 RequestContext,但是我怎样才能让 csrf_token 显示呢?

我想也许我可以以某种方式传递在 django-widgets 包中调用表单的上下文,但我不确定如何,因为这里没有请求......这里是表单被称为 widgets.py 的地方:

from django_widgets.base import Widget
from contact.forms import ContactForm

class ContactFormWidget(Widget):
    template = "contact/contact.html"
    def get_context(self):
        return {"contact_form":ContactForm()}

我也认为可能在 Widgets 类中,但同样,这里也没有请求对象:

from django.template.loader import get_template
from django.template.context import Context
from django.core.exceptions import ImproperlyConfigured
from django_widgets import loading

class WidgetBase(type):
    def __new__(cls, name, bases, attrs):
        # Make sure the Widget was specified properly
        if 'template' not in attrs:
            raise ImproperlyConfigured, "%s must specify a template." % name
        # Create the class.
        widget = type.__new__(cls, name, bases, attrs)
        # Register the class for future reference
        loading.registry.register(name, widget)
        return widget

class Widget(object):
    __metaclass__ = WidgetBase
    template = ""
    ctx = {}
    login_required = False

    def __init__(self):
        self.user = ''#user

    def get_context(self):
        """
        Provide any additional context required by the widget.
        This would be overridden when necessary.
        """
        return self.ctx

    def render(self):
        """
        Render the widget's template and return the rendered contents.
        """
        template = get_template(self.template)
        data = self.get_context()
        data.update(widget=self, user=self.user)
        return template.render(Context(data))

欢迎任何建议:)

谢谢

杰夫

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    您的代码实际上从未创建 RequestContext 对象,这需要导入和调用相关函数。查看代码链接,或this other csrf question 获取更多示例。

    请注意,如果您使用 HttpResponse,则必须创建自己的上下文,而 render_to_response 是为您完成此操作的快捷方式。

    【讨论】:

    • 嘿 John - 我知道我实际上并没有创建 RequestContext 对象,我没有呈现响应,我通过加载模板的类的 ajax 调用进行重定向。因此,我想知道如何访问 RequestContext 对象以便在我的模板中呈现 csrf 令牌。我能够覆盖表单上的构造函数,但是当我找到一种更好的方法来通过 ajax 加载这些 sn-ps 时,我将进行重构,看起来很脏。
    猜你喜欢
    • 2011-08-07
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 2015-02-05
    • 2019-10-08
    • 2011-08-10
    相关资源
    最近更新 更多