Login

Top-rated snippets

Snippet List

convenience parent class for UserProfile model

This is just a reusable convenience parent class to allow you to create and administer an automatic user profile class using the following code: class UserProfile(UserProfileModel): likes_kittens = models.BooleanField(default=True) Whenever a `User` object is created, a corresponding `UserProfile` will also be created. That's it. NB: You will still need to set `AUTH_PROFILE_MODULE` in your settings :-) (PS: It would also be nice to have the resulting class proxy the `User` object's attributes like django's model inheritance does, while still automatically creating a `UserProfile` object when a `User` object is created :-)

  • userprofile
Read More

Quantize decimal template filter

Takes a float number (23.456) and uses the decimal.quantize to round it to a fixed exponent. This allows you to specify the exponent precision, along with the rounding method. And is perfect for monetary formatting taking into account precision.

  • filter
  • decimal
  • quantize
Read More

Decorator to modify reverse() to render SSL urls

This snippet monkey-patches Django's reverse() method (use for generating URLs from vew functions and parameters) to allow certain areas of your site to automatically have URLs with the correct SSL domain in place. This saves you from having to use unnecessary redirects to guide users to an SSL-encrypted version of a page. This should still be used alongside a redirect-based method (such as [this snippet](http://www.djangosnippets.org/snippets/85/)) to ensure that the user can't access an unencrypted version of the page Simply add the code to the files mentioned in the code. This obviously won't work anywhere that doesn't use reverse(), the admin app seems to be an example of this.

  • url
  • ssl
  • reverse
  • permalink
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

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

entity encoded email-address

entity encoded string for a somewhat safer email-address. this filter encodes strings to numeric entities, almost every standard-browsers decodes the entities and display them the right way. needless to say that bots are smart, so this is not a 100% guaranteed spam prevention.

  • email
  • spam
  • prevention
Read More

Page numbers with ... like in Digg

Digg-like page numbering using inclusion tag. Usage in template: {% load pagination %} {% pagination yourpage %} Inclusion template `pagination.html`: {% load i18n %} <div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}" class="previous">{% trans "previous" %}</a> {% endif %} {% for pnum in begin %} {% ifequal page.number pnum %} <span class="current">{{ pnum }}</span> {% else %} <a href="?page={{ pnum }}">{{ pnum }}</a> {% endifequal %} {% endfor %} {% if middle %} <span class="continue">...</span> {% for pnum in middle %} {% ifequal page.number pnum %} <span class="current">{{ pnum }}</span> {% else %} <a href="?page={{ pnum }}">{{ pnum }}</a> {% endifequal %} {% endfor %} {% endif %} {% if end %} <span class="continue">...</span> {% for pnum in end %} {% ifequal page.number pnum %} <span class="current">{{ pnum }}</span> {% else %} <a href="?page={{ pnum }}">{{ pnum }}</a> {% endifequal %} {% endfor %} {% endif %} {% if page.has_next %} <a href="?page={{ page.next_page_number }}" class="next">{% trans "next" %}</a> {% endif %} </span> </div> Produces: previous 1 2 ... 4 5 6 7 **8** 9 10 11 12 ... 17 18 next Or: **1** 2 3 4 5 6 7 8 ... 17 18 next Or: previous 1 2 ... 10 11 12 13 14 15 16 **17** 18 next

  • tag
  • django
  • templatetag
  • pagination
  • digg
  • pages
Read More

nofollow filter for external links

Based on [svetlyak](http://www.djangosnippets.org/users/svetlyak/)'s [nofollow filter](http://www.djangosnippets.org/snippets/312/). This one processes only external URL's. Links with internal URL's will be returned unmodified. There's one gotcha; I preferred to have false positives instead of false negatives. So, it will nofollow `href="some/relative/path/"` for example. If you must do relative paths do it like this: <a href="./some/relative/path">link text</a>

  • filter
  • nofollow
Read More

Improved YAML serializer for large databases

I needed the ability to serialize and deserialize my database, which contains millions of objects. The existing XML serializer encountered spurious parse errors; the JSON serializer failed to handle UTF-8 even when it was asked to; and both the JSON and YAML serializers tried to keep all the representations in memory simultaneously. This custom serializer is the only one that has done the job. It uses YAML's "stream of documents" model so that it can successfully serialize and deserialize large databases.

  • serialize
  • database
  • yaml
Read More

Debug view: show available named URL patterns

Hook the show_url_patterns view function in to your URLconf to get a page which simply lists all of the named URL patterns in your system - useful for if your template developers need a quick reference as to what patterns they can use in the {% url %} tag.

  • urlconf
  • debug
  • debugging
  • urlpatterns
  • documentation
  • docs
Read More

wordbreak filter

usage: {{ object.content|wordbreak:"10" }} This means if any word is 10 characters or longer, a `&shy;` will be placed every 10 characters. This is to break long words which may break the appearance of a page. The output of this is HTML safe as the content has been conditionally escaped.

  • filter
  • custom-filter
  • wordbreak
  • word-break
  • long-words
Read More

Built-in Slugify with filtering.

This is based on snippets 29 and 43, both of which had good ideas, and I thought, "why not combine them?" Given the new_topic string above, the resulting slug will be: "test-long-string-which-has-many-words-here" John Crawford Note - requires python 2.5, for list comprehensions. Otherwise you could just use a for loop to build the clean_list.

  • django
  • slugify
Read More

3110 snippets posted so far.