【发布时间】: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