Login

Top-rated snippets

Snippet List

Limit ManyToMany fields in forms

Limit ManyToMany fields in forms. Hide the field, if only one item can be selected. e.g. For limit sites choices only to accessible sites. Also available via django-tools: http://code.google.com/p/django-tools/

  • forms
  • manytomany
Read More

match filter

A filter that re.matches a regex against a value. Useful for nav bars as follows: {% if location.path|match:"/$" %} class="current"{% endif %} For `location.path` see my [location context_processor](/snippets/1685/).

  • regex
  • match
  • nav
Read More

superSearch function for generating large OR queries

superSearch is intended to make it easier to make complex OR queries, thusly hitting the database less. EXAMPLE: Searching for a user named 'Eric Neuman' would be difficult because first_name and last_name are separate fields. However, with superSearch, it's a breeze. query = ['Eric Neuman'] f = ['first_name','last_name'] s = query.split(' ') m = ['icontains'] results = superSearch(User, f, m,s)

  • dynamic
  • q
  • query
  • kwargs
Read More

CategoriesField

If you have a relatively small finite number of categories (e.g. < 64), don't want to add a separate column for each one, and don't want to add an entire separate table and deal with joins, this field offers a simple solution. You initialize the field with a list of categories. The categories can be any Python object. When saving a set of categories, the field converts the set to a binary number based on the indices of the categories list you passed in. So if you pass in as your categories list [A,B,C,D] and set model.categories = [C,D], the integer stored in the database is 0b1100 (note that although the categories list has a left-to-right index, the binary number grows right-to-left). This means that if you change the order of your category list once you have data in the DB, you'll need to migrate the data over to the new format. Adding items to the list should be fine however. If you need to do filtering based on this field, you can use bitwise operators. Django currently (to my knowledge) doesn't support this natively, but most DBs have some bitwise operator support and you can use the extra function for now. For example, this query will select CheeseShop models that have the 'Gouda' in its cheeses field. `CheeseShop.objects.all().extra(where=['cheeses | %s = cheeses'], params=[CHEESES.index('Gouda')])`

  • field
  • categories
  • binary
Read More

StateField

Based on [CountryField](http://www.djangosnippets.org/snippets/494/).

  • model
  • field
  • state
  • statefield
Read More

RSS feed authentication

This is a very simple way of getting authenticated RSS feeds in django, by slightly changing the django.contrib.syndication.views 1) copy django/contrib/syndication/views.py into mysite/feeds/views.py 2) replace the contents of that file with the snippet 3) any feeds which you require login just add them to the auth_required list. In this case I require login for /feeds/mystuff/ so I make auth_required = ['mystuff'] My directory structure is like this: mysite/feeds/ views.py feedmodels.py feedmodels.py is just where you make your feed models (see http://docs.djangoproject.com/en/dev/ref/contrib/syndication/ where they give an example of "LatestEntries") [urls.py] - this is what I add in urls.py from mysite.feeds.feedmodels import Latest,MyPersonalStuff feeds = { 'latest':Latest, 'mystuff':MyPersonalStuff, } (r'^feeds/(?P<url>.*)/$', 'mysite.feeds.views.feed', {'feed_dict': feeds}), ###########################################################################

  • authentication
  • feed
  • rss
  • simple
Read More

Test IP against IP address+Subnet whitelist

Simple function that tests whether a given IP address is in a list of IP addresses or subnets. Requires `ipaddr`. Comes with Python 2.7 or 3.1, [downloadable here](http://code.google.com/p/ipaddr-py/) for earlier versions. More info on `ipaddr` [in Python 3.1 docs](http://docs.python.org/dev/py3k/library/ipaddr.html).

  • ip-address
  • whitelist
  • ipaddr
  • subnet
Read More

Template tag: Last x twitter msgs of user

A template tag which returns the n last tweets of a given user. It uses the twitter python lib. {% get_twitter_messages user foo limit 5 as tweets %} {% for tweet in tweets %} {{ tweet.text }} {{ tweet.time }} {{ tweet.url }} {% endfor %}

  • templatetag
  • twitter
Read More

web-key: Base64 Shared Secret for Access Control

At the [Internet Identity Workshop](http://iiw.idcommons.net/Iiw8) in May, 2009, I spoke to Alan Karp and Tyler Close of HP Labs about their research on authorization without identity. Here are my [Delicious links](http://delicious.com/sbwms/ZBAC) on the subject. This led me to write code to generate a "web-key," the shared secret needed to implement the access control method discussed. In his paper, Tyler Close recommends 70 bits for the shared secret, encoded as a 13-character Base32 string. I used 72 bits, so the secret is a 12-character, URL-safe Base64 string without padding characters. I'm new to Python and Django, so I welcome refinements!

  • password
  • web-key
  • webkey
  • zbac
  • access-control
Read More
Author: sbw
  • -1
  • 2

make templates fail loudly in dev

Add the line shown, or something similar, to your settings/dev.py, so that you can more clearly see when django is silently hiding errors in your template tags.

  • template
  • debugging
Read More

MultipleEmailsField

This is a custom field for multiple emails separated by comma. Original code was replaced by code from Django documentation: http://docs.djangoproject.com/en/dev/ref/forms/validation/ (MultiEmailField) so i'm not the author of the code, but just put it here to replace an outdated solution. Uses code from mksoft comment http://www.djangosnippets.org/snippets/1093/

  • multiple
  • forms
  • email
  • field
Read More

Non-Javascript select list navigator

If you need a simple select list (picklist) containing all site categories (or some other taxonomic group) and don't want to depend on Javascript, here's how to build a simple category navigator in Django, using HttpResponseRedirect.

  • form
  • select
  • picklist
Read More

UnitTesting without create/destroy database

This test runner is invoked with its own command: ./manage.py quicktest {usual test args follow} this creates a test database if it needs to and then DOES NOT delete it. subsequent uses of it start with the same database. this is for rapid test/development cycles usually running a single test. a single test can run in less than a second. when you need to alter the schema simply use the normal ./manage.py test which will delete the old test database and create a fresh one. it does not replace your normal test runner. it could probably be altered to even use your custom test runner. there are improvements to be done, and it will be included with a small testy app soon.

  • unittest
Read More

Lazy options on ModelForm fields - like setting a ModelChoiceField queryset from the view

Example view code: lazy_field_options = { 'field_name_that_is_m2m': { 'queryset': YourRelatedModel.objects.filter(groups=request.user.groups.all()), }, 'field_name_that_is_fk': { 'queryset': YourOtherRelatedModel.objects.filter(slug=request_slug), }, } modelform = YourModelForm(jpic_field_options=lazy_field_options) # after the modelform has called for parent __init__, it will set # options for each field if possible.

  • hack
  • form
  • queryset
  • modelchoicefield
  • modelform
  • modelmultiplechoicefield
Read More

3110 snippets posted so far.