Login

All snippets

Snippet List

Split a string to a list and add to select options

The template filter is use for split a string such as "foo|foobar|bar" to select option widget. You can define the splitter of the string by yourself. **Usage:** Add the code into templatetags folder of a installed app, then add below code into your template file. ` {% load split_as_option %} <select name="widget_name"> {{ QuerySet.values|split_as_option:"|" }} </select> `

  • template
  • filter
  • split
Read More

outliner template tag

Let's say you have a dataset and you want to render a page with sections/subsections/subsubsections down to some arbitrary depth and with arbitrary keys. For example, you might want to show cars broken out by year/price_range or price_range/year or price_range/manufacturer/model. The outliner template tag allows you to support multiple breakdowns of your data in a DRY sort of way. In order to use it, you supply four things: 1. a template for surrounding each subsection (think turtles all the way down) 2. a queryset (really anything iterable) 3. sectionizer dictionary/objects (see sample code, you must supply key_method) 4. inner html to render the lowest subsections The template provides the following: 1. It recursively uses each of your sectionizers' key methods to divvy up data sets. 2. It surrounds each section with templates of your choosing. 3. It renders the inner template for all the "leaf" elements of your tree. 4. It supplies some handy context vars for things like depth and outline ids. What this is not: 1. this is not for arbitrary tree data--think of the tree as fixed depth 2. this is not as simple as the regroup tag--if you have a concrete organization to your data, you should keep it simple and hand-code your templates

  • template
  • tree
  • outline
  • recursive
Read More

Cookie based Messages (deprecated)

DEPRECATED: Django has cookie based messages since version 1.2 This messages stores messages for the user in a cookie. I prefer this to session based messages, because the session column is a hot spot in the database if one user works with several browser tabs/windows.

  • x
Read More

Time toggle on mouseover template filter

Shows the timesince to the user and then on mouseover it will display the exact time for allowing the user to see the exact time. Example: shows "about 1 day, 3 hours ago" and then changes on mouseover to read "at 3:05pm on Wednesday 22nd April 2009"

  • date
  • time
  • usability
  • time-toggle
Read More

dumpdata/loaddata with MySQL and ForeignKeys, as django command

Based on [http://www.djangosnippets.org/snippets/662/](http://www.djangosnippets.org/snippets/662/) and updated to be runnable as custom django management command. Also added option support for --exclude=someapp --exclude=otherapp.SomeModel From original description: InnoDB tables within MySQL have no ability to defer reference checking until after a transaction is complete. This prevents most dumpdata/loaddata cycles unless the dump order falls so that referenced models are dumped before models that depend on them. Caveats 1. You use this snippet to dump the data and the built in manage.py loaddata to load the fixture output by this program. A similar solution could be applied to the XML processing on the loaddata side but this sufficed for my situations. 2. This code does not handle Circular or self-references. The loaddata for those needs to be much smarter

  • mysql
  • fixtures
  • dumpdata
  • command
Read More

Debug data for forms

I sometimes find that larger forms need data associated with them, but it's a bit of a pain to retype it each time when I'm debugging. The DebugForm base class lets you specify sets of testing data that will be inserted into your form if your project is in debug mode, randomly chosen from the DEBUG_DATA dict.

  • forms
  • debug
  • defaultdata
Read More

"Zoom in" on rendered HTML that the test client returns

If you have this as your base class for all unit tests you can do the following: class TestViews(BaseTestCase): def test_generated_stats(self): "test that certain stuff in the response" ...create some content for testing or use fixtures... response = self.client.get('/some/page/') # At this point response.content is a huge string filled with HTML tags and # "junk" that you don't need for testing the content thus making it difficult # to debug the generated HTML because it so huge. # So we can zoom in on the <div id="stats>...</div> node html = self._zoom_html(response.content, '#stats') # the variable 'html' will now be something like this: """ <div id="stats"> <p> <strong>2</strong> students<br/> <em>1</em> warning. </p> </div> """ # This makes it easier to debug the response and easier to test # against but the HTML might still be in the way so this would fail: self.assertTrue('2 students' in html) # will fail # To strip away all html use _strip_html() content = self._strip_html(html) # Now this will work self.assertTrue('2 students' in content) # will work It works for me and I find this very useful so I thought I'd share it.

  • css
  • test
  • client
  • lxml
  • lxml.html
Read More

Extended Form Wizard with ability to go backwards

This is an extended version of django wizard with the ability to go back and execute any step directly. To define next step to execute use the form field with the name "wizard_next_step". Don't forget to specify in your form the wizard_max_step field, so the knows the step number with the highest number, where the user was. An other improvement is the variable "wizard_data". It's a QueryDict with data from all wizard forms. It can be used to retrieve values from the field values of the forms from other steps. It could be helpfully for the latest step, where the user should see an overview of his input.

  • forms
  • wizard
Read More

Tuned IPAddressField with IPv4 & IPv6 support using Postgres Network Field type

I wanted to store ipv4 and ipv6 ip's in django but I wanted to use the postgresql inet network field type: http://www.postgresql.org/docs/8.3/static/datatype-net-types.html and I wanted to use IPy.py IP objects in python. I followed these very helpful examples along with the django documentation: http://vaig.be/2009/03/numeric-ip-field-for-django.html http://www.djangosnippets.org/snippets/1381/ It took me awhile to figure out how this works (not that I completely understand it now..) and figured I would share it. If anyone finds problems with this or can make it better I will definitely use it.

  • model
  • field
  • ip
  • custom
  • ip-address
  • ip-addresses
  • ipv4
  • ipv6
  • ipy
  • postgresql-network-field
Read More

ABN and ACN Form Fields

ACNField - Australian Company Number Form Field ABNField - Australian Business Number Form Field Any feedback / Improvements Appreciated.

  • fields
  • forms
  • abn
  • acn
Read More

mini_render_to_response

You need the mini-detector middleware installed [http://www.iterasi.net/openviewer.aspx?sqrlitid=-e2dfig9w0yrclxaigp-uw](http://www.iterasi.net/openviewer.aspx?sqrlitid=-e2dfig9w0yrclxaigp-uw). This is a drop in replacement to render_to_response. When using mini_render_to_response it will try to load a version of your template with &#157;mini at the end. For example "home_mini.html" instead of "home.html". If it doesn't find the _mini version it falls back to the regular "home.html" version of your template. Easy way to maintain a "small screen" version of your templates for iPhone or other small screen devices.

  • templates
  • render
  • iphone
  • mini
Read More

highlight pattern

Encloses all matches of a pattern between the opentag and closetag string. ` {% with "this is a large test" as a %} {{ a|highlightpattern:"a" }} {% endwith %} ` yields this is <b>a</b> l<b>a</b>rge test

  • filter
  • highlight
  • pattern
Read More

Widget for Money values on Geraldo Reports

This is a widget for decimal/money/currency fields on **Geraldo Reports**. When you use Geraldo to write reports, decimal fields must be formatted using **get_value** lambda attribute, because ObjectValue doesn't know what mask you want to use. With this widget, you just copy it into a common use Python file, import into your reports file and use it replacing ObjectValue on elements for fields you must be formatted as money format. **Example:** from geraldo import Report, ReportBand, ObjectValue from utils.reports import DecimalObjectValue class ReportCustomers(Report): title = u'Customers List' page_size = A4 class band_detail(ReportBand): height = 0.5*cm elements = [ ObjectValue(attribute_name='id', top=0.1*cm), DecimalObjectValue(attribute_name='salary', left=26.2*cm, top=0.1*cm, format='%0.03f'), ]

  • geraldo
Read More

Widget for DateTime values on Geraldo Reports

This is a widget for date/time fields on **Geraldo Reports**. When you use Geraldo to write reports, date/time fields must be formatted using **get_value** lambda attribute, because ObjectValue doesn't know what mask you want to use. With this widget, you just copy it into a common use Python file, import into your reports file and use it replacing ObjectValue on elements for fields you must be formatted as date/time format. **Example:** from geraldo import Report, ReportBand, ObjectValue, landscape from utils.reports import DateTimeObjectValue class ReportPhoneList(Report): title = u'Phone List' page_size = landscape(A4) class band_detail(ReportBand): height = 0.5*cm elements = [ ObjectValue(attribute_name='id', top=0.1*cm), DateTimeObjectValue(attribute_name='birth_date', left=26.2*cm, top=0.1*cm, format='%m/%d/%Y'), ]

  • geraldo
Read More

Template filter for formatting negative numbers

I have a need to conditionally format a negative number, a hedgefund's daily price change, Excel style. i.e. show a negative number as a parenthesized number instead of a negative sign. Here is a filter that will do that and more, solving a more general case. See the doctest for examples.

  • template
  • filter
  • format
  • currency
  • math
Read More

3109 snippets posted so far.