Login

All snippets

Snippet List

Forms splitted in fieldsets

This template tag build a Form splitted in fieldsets. The fieldsets are configured with a second parameter, that is a tuple like the one used in the Admin class in models in the attribute "fields". You pass to the template the form and the tuple and than use them as parameters for the templatetag. You can take a look at the source and modify It to build forms the way you like. It is very useful If you do not like the way Django build forms with the methods as_p, as_ul or as_table and also do not like to write html by hand.

  • forms
  • fieldset
  • form
  • fieldsets
Read More

dumpdata/loaddata with MySQL and ForeignKeys (Revision 2)

nnoDB 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. This code uses Ofer Faigon's topological sort to sort the models so that any models with a ForeignKey relationship are dumped after the models they reference. class Entry(models.Model): txt = .... class Comment(models.Model): entry = models.ForeignKey(Entry) This code will ensure that Entry always gets dumped before Comment. Fixtures are an important part of the django Unit Testing framework so I really needed to be able to test my more complicated models. 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
Read More

Tags & filters for rendering search results

Use these tags and filter when you're rolling your own search results. This is intended to be a whole templatetags module. I keep it in my apps as `templatetags/search.py`. These should not be used to perform search queries, but rather render the results. ### Basics There are three functions, each has both a tag *and* a filter of the same name. These functions accept, at a minimum, a body of text and a list of search terms: * **searchexcerpt**: Truncate the text so that each search term is shown, surrounded by some number of words of context. * **highlight**: Wrap all found search terms in an HTML span that can be styled to highlight the terms. * **hits**: Count the occurrences of the search terms in the text. The filters provide the most basic functionality as described above, while the tags offer more options as arguments, such as case sensitivity, whole word search, and saving the results to a context variable. ### Settings Defaults for both the tags and filters can be changed with the following settings. Note that these settings are merely a convenience for the tags, which accept these as arguments, but are necessary for changing behavior of the filters. * `SEARCH_CONTEXT_WORDS`: Number of words to show on the left and right of each search term. Default: 10 * `SEARCH_IGNORE_CASE`: False for case sensitive, True otherwise. Default: True * `SEARCH_WORD_BOUNDARY`: Find whole words and not strings in the middle of words. Default: False * `SEARCH_HIGHLIGHT_CLASS`: The class to give the HTML span element when wrapping highlighted search terms. Default: "highlight" ### Examples Suppose you have a list `flatpages` resulting from a search query, and the search terms (split into a list) are in the context variable `terms`. This will show 5 words of context around each term and highlight matches in the title: {% for page in flatpages %} <h3>{{ page.title|highlight:terms }}</h3> <p> {% searchexcerpt terms 5 %} {{ page.content|striptags }} {% endsearchexcerpt %} </p> {% endfor %} Add highlighting to the excerpt, and use a custom span class (the two flags are for case insensitivity and respecting word boundaries): {% highlight 1 1 "match" %} {% searchexcerpt terms 5 1 1 %} {{ page.content|striptags }} {% endsearchexcerpt %} {% endhighlight %} Show the number of hits in the body: <h3>{{ page.title }} (Hits: {{ page.content|striptags|hits:terms }}) </h3> All tags support an `as name` suffix, in which case an object will be stored in the template context with the given name; output will be suppressed. This is more efficient when you want both the excerpt and the number of hits. The stored object depends on the tag: * **searchexcerpt**: A dictionary with keys "original" (the text searched), "excerpt" (the summarized text with search terms), and "hits" (the number of hits in the text). * **searchcontext**: A dictionary with keys "original", "highlighted", and "hits", with obvious values. * **hits**: Just the number of hits, nothing special. Getting both the hits and the excerpt with "as": {% searchexcerpt terms 3 as content %} {{ page.content|striptags }} {% endsearchexcerpt %} <p>Hits: {{ content.hits }}<br>{{ content.excerpt }}</p> ### More For more examples see [Brian Beck's Text Adventure][announcement]. [announcement]: http://blog.brianbeck.com/post/29707610

  • filter
  • tag
  • search
  • templatetags
  • context
  • highlight
  • excerpt
Read More

TemplateTag to Split a List into Uniform Chunks

Creates a template tag called "split_list" which can split a list into chunks of a given size. For instance, if you have a list 'some_data', and you want to put it into a table with three items per row, you could use this tag: {% split_list some_data as chunked_data 3 %} Given a some_data of [1,2,3,4,5,6], the context variable 'chunked_data' becomes [[1,2,3],[4,5,6]] This is useful for creating rows of equal numbers of items. Thanks to the users of #django (pauladamsmith, Adam_G, and ubernostrum) for advice and pointers, thanks to Guyon Mor&eacute;e for writing the chunking recipe that this tag is based on.

  • templatetag
  • split
  • list
Read More

PDF generation directly using HTML

This is an extract of an example for use of "pisa" <http://www.htmltopdf.org> in "django". It shows the easiest way possible to create PDF documents just using HTML and CSS. In "index" we see the definition of the output of a form in which HTML code can be typed in and then on the fly a PDF will be created. In "ezpdf_sample" we see the use of templates and contexts. So adding PDF to your existing Django project could be just a matter of some lines of code.

  • pdf
  • html
  • css
Read More

YUI editor for flatpages inside admin interface

This template extends the change form for the flatpages inside the admin interface to use [Yahoo! User Interface Library](http://developer.yahoo.com/yui/)'s [Rich Text Editor](http://developer.yahoo.com/yui/editor/). It should be named `change_form.html` and be placed in the `admin/flatpages/flatpage/` directory of the project templates.

  • admin
  • flatpages
  • yui-editor
Read More

URL based breadcrumbs

This is a simple URL based breadcrumb filter I'm using on a site I'm currently building. To use it, just throw the code into template-tag file, and simply pass the current url in a page template like so {{ request.get_full_path|breadcrumbs }} As an example of how to style it, wrap it in a unordered list with an id of breadcrumb, and then in your styles use #breadcrumb li { display: inline; }. On a contact form for a site user, this will produce something along the lines of you are here : [home](/) » [users](/users/) » [username](/username/) » contact form Hopefully someone may find it useful.

  • filter
  • breadcrumbs
Read More

Fire Eagle example: views.py from wikinear.com

The views.py used by [wikinear.com](http://wikinear.com/) - see [http://simonwillison.net/2008/Mar/22/wikinear/](http://simonwillison.net/2008/Mar/22/wikinear/) For a more comprehensive API wrapper for Fire Eagle, take a look at [fireeagle_api.py](http://github.com/SteveMarshall/fire-eagle-python-binding/tree/master/fireeagle_api.py)

  • location
  • fireeagle
  • oauth
Read More

Use MEDIA_URL in flatpages

This is a template filter to enable the use of the MEDIA_URL setting in content from the flatpages database table. It searches for {{ MEDIA_URL }} and replaces it with that found in your settings. Note: To set up, drop the above code into a file called `media_url.py` in your templatetags directory in one of your INSTALLED_APPS, and add the filter to your flatpages template like so: {% load media_url %} {{ flatpage.content|media_url }}

  • filter
  • flatpages
Read More

Middleware to remove the WWW from the URL

Works like the [PREPEND_WWW](http://www.djangoproject.com/documentation/settings/#prepend-www) setting but, instead of adding, it removes the www. Usage: In the settings file add the UrlMiddleware to the middleware list and set REMOVE_WWW = True

  • middleware
Read More

Searchable Media

This app allows you to utilize mysql's fulltext searching over multiple models and multiple apps, letting the site search seem more intuitive, yet still allow your content to be very structured. Essentially, it creates an entire new model that associates objects to a chunk of text to search efficiently over (and index), using the contenttypes app. Simply add the post_save events to your existing models for things you want to be searched.

  • search
  • media
  • fulltext
  • mixed
Read More

Alternative to User.get_profile()

**This is an alternative to User.get_profile.** Rather than having you call `User.get_profile` directly, this retrieves the profile instance for a `User` and attaches the fields from the profile to the `User` object when instantiated. The special methods for `DateField`, `FileField`, `ImageField` and fields with `choices` are also created. Since the profile object still has to be retrieved from the database before its fields can be added to the `User`, the costs for using this might outweigh the rewards unless you are heavily using profiles. To install, place it in a module on your `PYTHONPATH` and add it to `INSTALLED_APPS`.

  • user
  • profile
  • auth
  • userprofile
  • profiles
Read More

Simple Exception Response for AJAX debugging

When debugging AJAX with Firebug, if a response is 500, it is a pain to have to view the entire source of the pretty exception page. This is a simple middleware that just returns the exception without any markup. You can add this anywhere in your python path and then put it in you settings file. It will only unprettify your exceptions when there is a XMLHttpRequest header. Tested in FF2 with the YUI XHR. Comments welcome. EDIT: I recently changed the request checking to use the is_ajax() method. This gives you access to these simple exceptions for get requests as well (even though you could just point your browser there).

  • middleware
  • ajax
  • exception-handling
Read More

unique validation for ModelForm

Inherit your forms from model from this ModelForm and it will check all the database fields with unique=True in `is_valid()`. This is a hack around [#5736](http://code.djangoproject.com/ticket/5736). It is actually a part of a grand problem mentioned in [#4895](http://code.djangoproject.com/ticket/4895). You can use this hack until the issue is fully resolved.

  • newforms
Read More

3110 snippets posted so far.