Skip to content

Instantly share code, notes, and snippets.

@dfalk
Created February 29, 2012 11:39
Show Gist options
  • Save dfalk/1940240 to your computer and use it in GitHub Desktop.
Save dfalk/1940240 to your computer and use it in GitHub Desktop.
Using django-floppyforms with django-sekizai

This is a bridge between django-floppyforms and django-sekizai.

This lets you define custom floppyforms widgets and move the css / js parts to the top or the bottom of the page.

Just write a floppyforms widget with a custom template. In that template, use {% addtoblock "js" %} to inject some data in a sekizai block. In the template that renders your form, make sure you use iterate over your fields and use {% widget field %} to render instead of {{ field }}.

Note that to render your widget separately in the console, you'll need to add enable_sekizai in one of your app's templatetags and do {% load enable_sekizai %}{% enable_sekizai %}. Note that anything inside the {% addtoblock %} tags will disappear but your widgets can be rendered in the console.

Not sure this plays well with hidden widgets. Use at your own risk.

"""This template tag loads the SekizaiContext if it's not present.
Useful for rendering widgets in the console when there's not request"""
from classytags.core import Tag
from sekizai.settings import VARNAME
from sekizai.context_processors import sekizai
from django import template
register = template.Library()
class EnableSekizai(Tag):
name = 'enable_sekizai'
def render_tag(self, context):
if VARNAME not in context:
context.update(sekizai())
return ''
register.tag(EnableSekizai)
from classytags.core import Tag, Options
from classytags.arguments import Argument
from django import template
register = template.Library()
class Widget(Tag):
name = 'widget'
options = Options(
Argument('field'),
)
def render_tag(self, context, field):
widget = field.field.widget
attrs = {}
auto_id = field.auto_id
if auto_id and 'id' not in attrs and 'id' not in widget.attrs:
attrs['id'] = auto_id
name = field.html_name
widget_context = widget.get_context(name, field.value(), attrs=attrs)
context.push()
context.update(widget_context)
output = template.loader.render_to_string(widget.template_name, context)
context.pop()
return output
register.tag(Widget)
{% load floppyforms_tags %}
{% csrf_token %}
{% if form.errors and not form.non_field_errors %}
<p class="errorlist">Please correct the errors below and submit the form
again.</p>
{% endif %}
{{ form.non_field_errors }}
{% for field in form %}
{% if not field.is_hidden %}
<div class="field">
<div class="grid_2 alpha">
<h4>{{ field.label_tag }}</h4>
{% if field.help_text %}<p class="helptext">{{ field.help_text|safe }}</p>{% endif %}
</div>
<div class="grid_4 omega">
{{ field.errors }}
<p>{% widget field %}</p>
</div>
<div class="clear"></div>
</div>
{% else %}{% widget field %}{% endif %}
{% endfor %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment