使用django-widgets的RequestContext使CSRF正常工作

时间:2011-07-29 13:37:53

标签: django django-forms

我正在使用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:< / p>

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))

欢迎任何建议:)

由于

杰夫

1 个答案:

答案 0 :(得分:0)

您的代码实际上从未创建 RequestContext对象,这需要导入并调用相关函数。请参阅代码链接,或this other csrf question了解更多示例。

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