Login

Most bookmarked snippets

Snippet List

filter dates to user profile's timezone

I have users in many timezones and I let them set their preferred display timezone in their user profile as a string (validated aginst the pytz valid timezones). This is a filter that takes a datetime as input and as an argument the user to figure out the timezone from. It requires that there is a user profile model with a 'timezone' field. If a specific user does not have a user profile we fall back on the settings.TIME_ZONE. If the datetime is naieve then we again fallback on the settings.TIME_ZONE. It requires the 'pytz' module: [http://pytz.sourceforge.net/](http://pytz.sourceforge.net/) Use: `{{ post.created|user_tz:user|date:"D, M j, Y H:i" }}` The example is assuming a context in which the 'user' variable refers to a User object.

  • filter
  • timezone
  • userprofile
Read More

Sanitize text field HTML (here from the Dojo Toolkit Editor2 widget)

When using a JavaScript WYSIWYG editor widget for text area content, the resulting HTML should be sanitized so no unallowed HTML tags (esp. script tags) are present. The [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) library handles HTML processing in the solution presented above, so you should place it in the Python path. The snippet also assumes that you have [the Dojo Toolkit](http://dojotoolkit.org/) and its Editor2 widget loaded on your page. **Note**: this snippet was originally written for use with Dojo Toolkit 0.4, and it hasn't been updated for 0.9 or 1.0.

  • forms
  • html
  • wysiwyg
  • dojo
  • security
  • sanitize
Read More

Filter on Multiple M2M Objects Simultaneously

This snippet should allow you to do queries not before possible using Django's ORM. It allows you to "Split" up the m2m object you are filtering on. This is best described by example: Suppose you have `Article` and `Tag`, where `Article` has a m2m relation with `Tag` (`related_name = 'tag'`). If I run: from django.db.models.query import Q Article.objects.filter(Q(tag__value = 'A') & Q(tag__value = 'B')) > # no results I would expect to get no results (there are no tags with both a value of 'A' and 'B'). However, I *would* like to somehow get a list of articles with tags meeting that criteria. Using this snippet, you can: from django.db.models.query import Q from path.to.qsplit import QSplit Article.objects.filter(QSplit(Q(tag__value = 'A')) & QSplit(Q(tag__value = 'B'))) > # articles with both tags So now they are split into different `Tag` entries. Notice how the `QSplit()` constructor takes a `Q` object---it's possible to give this any complicated Q-type expression.

  • models
  • q
  • m2m
  • db
  • orm
Read More

Authenticate with Email Address

This code gives you the ability to authenticate a user by their email address instead of the username. I've also added the ability to authenticate via LDAP. Some code used from this [snippet](http://www.djangosnippets.org/snippets/74/)

  • admin
  • user
  • email
  • authenticate
  • ldap
Read More

Akismet Webservice

A short little bit of code to test for comment spam against Akimet. Use: a = Akismet('<AkismetKey>', 'http://sneeu.com/blog/') a.verify_key() print a.comment_check( comment_author='...', comment_author_email='[email protected]', user_ip='10.0.0.1', comment_content="""Comment content!""" )

  • rest
  • python
  • akismet
  • spam
  • webservice
  • comment
Read More

Regular Expression Replace Template Filter

This will perform a regular expression search/replace on a string in your template. `{% load replace %}` `{{ mystring|replace:"/l(u+)pin/m\1gen" }}` If: `mystring = 'lupin, luuuuuupin, and luuuuuuuuuuuuupin are lè pwn'` then it will return: `mugen, muuuuuugen, and muuuuuuuuuuuuugen are lè pwn` The argument is in the following format: [delim char]regexp search[delim char]regexp replace

  • regex
  • regular-expressions
  • templates
  • filters
Read More

Multilingual Models

A way to implement models with translatable content. The translatable field of the default language has no extension, like "title" and the translations have extensions postfixes "_<two-letter language code>", like "title_la" or "title_mn". Method get_title() in this case returns the translation of the currently chosen language or the title of the default language, if the translation is not set. The class XFieldList overrides the default list class and is used for modifying ordering and list_display settings according the chosen language. For example, when the German language is chosen, the list of translatable content objects will be ordered by German titles (not English). *At the time when the list of field names is assigned to ordering or list_display (at the import of the model), the currently chosen language is still not known. But the language is known when ordering and list_display lists are used in contributed administration or elsewhere.* The XFieldList returns the modified values of the passed-in list, when its methods/properties are triggered. XFieldList transforms field names ending "_" (except the ones beginning with "__", like "__str__") to appropriate translations according the currently chosen language. For example ['title_', 'content_', 'is_published'] will be changed to ['title', 'content', 'is_published'] for the English language and to ['title_lt', 'content_lt', 'is_published'] for the Lithuanian language. *The best practice is to put XFieldList into a separate file and import it from different apps whenever needed.* It's worth mentioning that one implementing this should also know about [Django internationalization](http://www.djangoproject.com/documentation/i18n/).

  • i18n
  • l10n
  • translations
  • multilingual
Read More

Django-pagination with Bootstrap CSS

A quick django-pagination template fix to make it work with Bootstrap CSS Library 2.0. Usage: Install django-pagination and save the snippet in templates/pagination/pagination.html then {% paginate %} will work fine. See [Django-paginaation on Bootstrap CSS](http://ronbeltran.blogspot.com/2012/05/django-pagination-bootstrap-css.html)

  • django-pagination
  • bootsrap-css
Read More

Simple DRY Tabs using Django 1.3

I was just playing around with Django 1.3 and came across the new 'with' addition to the include tag. I thought this was a super elegant way to implement a DRY tab menu without having to move menu code into the views. Enjoy!

  • menu
  • dry
  • tabs
  • menus
  • tabbed
  • tab
Read More

Auto-create Django admin user during syncdb

This avoids the frustrating step of having to set up a new admin user every time you re-initialize your database. Put this in any `models` module. In this example I use `common.models`. Adapted from http://stackoverflow.com/questions/1466827/

  • django
  • admin
  • user
  • syncdb
  • manage
  • automatic
  • adminuser
  • admin-user
Read More

TwitterBackend

TwitterBackend is the twitter authentication backend. This backend makes use of OAuth based "Sign-in with Twitter" Configure your settings.py as per [Django - Specifying Authentication Backends](http://docs.djangoproject.com/en/dev/topics/auth/#specifying-authentication-backends)

  • django
  • authentication
  • python
  • backend
  • twitter
  • oauth
Read More

Ping All Search Engines

Nothing much to see here. Needed this little puppy for work and figured I and others will need it for other projects. Enjoy!

  • search
  • google
  • all
  • ping
  • engines
  • yahoo
  • live
  • ask
Read More

Validate by file content type and size

A simple way to handle file validation by checking for a proper content_type and by making sure that the file does not go over its limit upload size limit. In the example I am checking to make sure the file is an image or a video file then I check to make sure that the file is below the max upload limit. if conditions are not met, then a validation error is raised

  • forms
  • validation
  • filefield
  • file
Read More

minimal nginx conf to split get/post requests

After a point the sql server becomes the bottleneck in lots of web application, and to scale, master-slave replication with single master, multiple slave is recommended. This setup with nginx can be used to accomplish traffic distribution between master and slave based on request method.

  • middleware
  • nginx
  • loadbalancing
  • master-slave
Read More

3110 snippets posted so far.