Permalink
Browse files

Always pass a context into FormForForm.

  • Loading branch information...
stephenmcd committed Mar 24, 2012
1 parent 338d411 commit 49dfe5caf2ce026a79f0aa62b1ca6243faad2a35
@@ -7,10 +7,10 @@
from django.forms.extras import SelectDateWidget from django.forms.extras import SelectDateWidget
from django.core.files.storage import FileSystemStorage from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.template import Template
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.template.base import Origin, Template, Context, TemplateDoesNotExist
from forms_builder.forms import fields from forms_builder.forms import fields
from forms_builder.forms.models import FormEntry, FieldEntry from forms_builder.forms.models import FormEntry, FieldEntry
@@ -71,18 +71,13 @@ class Meta:
model = FormEntry model = FormEntry
exclude = ("form", "entry_time") exclude = ("form", "entry_time")
def __init__(self, form, *args, **kwargs): def __init__(self, form, context, *args, **kwargs):
""" """
Dynamically add each of the form fields for the given form model Dynamically add each of the form fields for the given form model
instance and its related field model instances. instance and its related field model instances.
""" """
self.form = form self.form = form
self.form_fields = form.fields.visible() self.form_fields = form.fields.visible()
self.context_dict = kwargs.get('context')
self.context = None
if self.context_dict:
self.context = Context(self.context_dict)
del(kwargs['context'])
# If a FormEntry instance is given to edit, populate initial # If a FormEntry instance is given to edit, populate initial
# with its field values. # with its field values.
field_entries = {} field_entries = {}
@@ -107,7 +102,8 @@ def __init__(self, form, *args, **kwargs):
try: try:
self.initial[field_key] = field_entries[field.id] self.initial[field_key] = field_entries[field.id]
except KeyError: except KeyError:
self.initial[field_key] = self.fill_in(field_key, field.default) default = Template(field.default).render(context)
self.initial[field_key] = default
self.fields[field_key] = field_class(**field_args) self.fields[field_key] = field_class(**field_args)
# Add identifying CSS classes to the field. # Add identifying CSS classes to the field.
css_class = field_class.__name__.lower() css_class = field_class.__name__.lower()
@@ -121,16 +117,6 @@ def __init__(self, form, *args, **kwargs):
text = field.placeholder_text text = field.placeholder_text
self.fields[field_key].widget.attrs["placeholder"] = text self.fields[field_key].widget.attrs["placeholder"] = text
def fill_in(self, field_key, default):
return self.render_string(default)
def render_string(self, string):
if self.context:
t = Template(string)
return t.render(self.context)
else:
return string
def save(self, **kwargs): def save(self, **kwargs):
""" """
Get/create a FormEntry instance and assign submitted values to Get/create a FormEntry instance and assign submitted values to
@@ -32,7 +32,7 @@ def render(self, context):
return "" return ""
t = get_template("forms/includes/built_form.html") t = get_template("forms/includes/built_form.html")
context["form"] = form context["form"] = form
context["form_for_form"] = FormForForm(form) context["form_for_form"] = FormForForm(form, context)
return t.render(context) return t.render(context)
@@ -2,7 +2,7 @@
from django.conf import settings from django.conf import settings
from django.contrib.auth.models import User, AnonymousUser from django.contrib.auth.models import User, AnonymousUser
from django.contrib.sites.models import Site from django.contrib.sites.models import Site
from django.template import Context, Template from django.template import RequestContext, Template
from django.test import TestCase from django.test import TestCase
from forms_builder.forms.models import Form, STATUS_DRAFT, STATUS_PUBLISHED from forms_builder.forms.models import Form, STATUS_DRAFT, STATUS_PUBLISHED
@@ -80,16 +80,13 @@ def test_tag(self):
Test that the different formats for the ``render_built_form`` Test that the different formats for the ``render_built_form``
tag all work. tag all work.
""" """
class Request(object):
pass
request = Request()
setattr(request, "user", AnonymousUser())
form = Form.objects.create(title="Tags", status=STATUS_PUBLISHED) form = Form.objects.create(title="Tags", status=STATUS_PUBLISHED)
context = {"form": form, "request": request} request = type("Request", (), {"META": {}, "user": AnonymousUser()})()
context = RequestContext(request, {"form": form})
template = "{%% load forms_builder_tags %%}{%% render_built_form %s %%}" template = "{%% load forms_builder_tags %%}{%% render_built_form %s %%}"
formats = ("form", "form=form", "id=form.id", "slug=form.slug") formats = ("form", "form=form", "id=form.id", "slug=form.slug")
for format in formats: for format in formats:
t = Template(template % format).render(Context(context)) t = Template(template % format).render(context)
self.assertTrue(form.get_absolute_url(), t) self.assertTrue(form.get_absolute_url(), t)
@@ -23,15 +23,16 @@ def form_detail(request, slug, template="forms/form_detail.html"):
if form.login_required and not request.user.is_authenticated(): if form.login_required and not request.user.is_authenticated():
return redirect("%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME, return redirect("%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME,
urlquote(request.get_full_path()))) urlquote(request.get_full_path())))
args = (form, request.POST or None, request.FILES or None) request_context = RequestContext(request)
args = (form, request_context, request.POST or None, request.FILES or None)
form_for_form = FormForForm(*args) form_for_form = FormForForm(*args)
if request.method == "POST": if request.method == "POST":
if not form_for_form.is_valid(): if not form_for_form.is_valid():
form_invalid.send(sender=request, form=form_for_form) form_invalid.send(sender=request, form=form_for_form)
else: else:
entry = form_for_form.save() entry = form_for_form.save()
fields = ["%s: %s" % (v.label, form_for_form.cleaned_data[k]) fields = ["%s: %s" % (v.label, form_for_form.cleaned_data[k])
for (k, v) in form_for_form.fields.items()] for (k, v) in form_for_form.fields.items()]
subject = form.email_subject subject = form.email_subject
if not subject: if not subject:
subject = "%s - %s" % (form.title, entry.entry_time) subject = "%s - %s" % (form.title, entry.entry_time)
@@ -45,7 +46,7 @@ def form_detail(request, slug, template="forms/form_detail.html"):
msg.send() msg.send()
email_from = email_to or email_from # Send from the email entered. email_from = email_to or email_from # Send from the email entered.
email_copies = [e.strip() for e in form.email_copies.split(",") email_copies = [e.strip() for e in form.email_copies.split(",")
if e.strip()] if e.strip()]
if email_copies: if email_copies:
msg = EmailMessage(subject, body, email_from, email_copies) msg = EmailMessage(subject, body, email_from, email_copies)
for f in form_for_form.files.values(): for f in form_for_form.files.values():
@@ -54,8 +55,8 @@ def form_detail(request, slug, template="forms/form_detail.html"):
msg.send() msg.send()
form_valid.send(sender=request, form=form_for_form, entry=entry) form_valid.send(sender=request, form=form_for_form, entry=entry)
return redirect(reverse("form_sent", kwargs={"slug": form.slug})) return redirect(reverse("form_sent", kwargs={"slug": form.slug}))
context = {"form": form, "form_for_form": form_for_form} context = {"form": form}
return render_to_response(template, context, RequestContext(request)) return render_to_response(template, context, request_context)
def form_sent(request, slug, template="forms/form_sent.html"): def form_sent(request, slug, template="forms/form_sent.html"):

0 comments on commit 49dfe5c

Please sign in to comment.