Login

All snippets written in Python

Snippet List

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

Soft hyphenation (&shy;) template filter using PyHyphen

This template filter is meant to insert soft hyphens ([&shy; entities](http://www.cs.tut.fi/~jkorpela/shy.html)) in text whever it can. For this is relies on a **recent** checkout of the [PyHyphen](http://code.google.com/p/pyhyphen/) interface to the hyphen-2.3 C library, which is also used by Mozilla and OpenOffice.org. It takes two optional parameters: the language to hyphenate in and the minimum word length to consider for hyphenation. If no language is given, the default language from the settings file is used. The second parameter defaults to 5 characters. Usage example: {% load hyphenation %} {{ object.text|hyphenate:"nl-nl,6" }}

  • template
  • filter
  • text
  • hyphenation
  • hyphen
  • soft
  • &shy;
  • pyhyphen
  • typografy
Read More

twitterize filter

This filter links twitter user names prefixed with '@', hash tags, and URLs. Usage example: `{{var|twitterize}}` Note: Do not use this in conjunction with the urlize filter. Twitterize does this for you.

  • filter
  • twitter
  • hash-tags
  • @replies
Read More

url extension mechanism

Executive summary: url "include" on steroids--granular extra parms and validate names in passing We maintain multiple Django applications, and we use the excellent built-in include mechanism to allow one urls.py to borrow from another: http://docs.djangoproject.com/en/dev/topics/http/urls/ If you scroll down to the section entitled "Passing extra options to include," you will see this annoying limitation: ''' Note that extra options will always be passed to every line in the included URLconf, regardless of whether the line's view actually accepts those options as valid. For this reason, this technique is only useful if you're certain that every view in the included URLconf accepts the extra options you're passing. ''' My snippet overcomes this limitation, allowing you to extend individual urls without polluting the namespace. The function also has the nice side effect of validating that the parent hasn't changed names on you.

  • url
  • extend
  • include
Read More

2956 snippets posted so far.