I am using http://code.google.com/p/django-widgets/ with a project, in my view I am using AJAX to send an email like so:
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'] )
My problem is that the csrf_token in my template does not show up. I understand it is because I don't have the RequestContext in my template, but how could I get csrf_token to display with this?
I thought maybe I can somehow pass in the Contexts where the form gets called in the django-widgets package but I am not sure how since there is no request here... here's where the form gets called 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()}
I also thought maybe in the Widgets class, but again, no request object here either:
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 t开发者_C百科he 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))
Any suggestions are welcome :)
Thanks
Jeff
Your code never actually creates a RequestContext object, which requires importing and calling the relevant function. See the link for code, or this other csrf question for more examples.
Note that if you use HttpResponse, then you have to create your own context, whereas render_to_response is a shortcut that does it for you.
精彩评论