Login

All snippets written in Python

Snippet List

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

location context_processor

A simple context_processor to include location info. Useful for permalinks, site name references, and navigation bars. For example: {% if location.path|match:"/$" %} class="current"{% endif %} See also my [match filter](/snippets/1686/).

  • url
  • path
  • location
  • nav
Read More

Django Template "include_raw" tag

At WWU Housing, we started using the [Tempest jQuery plugin](http://plugins.jquery.com/project/tempest) for javascript templating, which has the same {{ var }} syntax as Django's templating. We wanted to be able to use the same templates in our server-side python and our client-side js, so we had to have a way of including the unrendered template for the js. At the same time, for convenience, it had to be modular so we could push the same code from our dev- to our live-server and not worry about absolute paths (which is why the {% ssi %} tag did not work). So the {% include_raw %} tag was born.

  • template
  • django
  • parse
  • include
  • ssi
Read More

is_dirty and dict of changed values

When you call model.changed_columns() you get a dict of all changed values. When you call model.is_dirty() you get boolean whether or not the object has been changed since last save Based on an answer here:http://stackoverflow.com/questions/110803/dirty-fields-in-django but fixed and added is_dirty

  • django
  • models
  • save
  • dirty
Read More

CSV to JSON Fixture

**This script converts a CSV file into a JSON file ready to be imported via `manage.py loaddata` like any other fixture data.** It can be used manually to do a one-time conversion (for placing into a /fixtures folder), or used in a fabric script that automatically converts CSV to JSON live then runs `loaddata` to import as fixture data. To run script: >`csv2json.py input_file_name model_name` > >e.g. csv2json.py airport.csv app_airport.Airport > >Note: input_file_name should be a path relative to where this script is. **Scripts depends on simplejson module.** The module can just be placed in a sub-folder to the script to make it easy to import. If you use the same Python binary that you use for your Django site, you could use the Django import instead: `from django.utils import simplejson` **File Input/Ouptut formats:** Assumes CSV files are saved with LF line endings, and that first line has field values. First column is the model's pk field. Sample CSV input: id,ident,name,city,state 1,00C,Animas Air Park,Durango,CO 6,00V,Meadow Lake,Colorado Springs,CO 7,00W,Lower Granite State,Colfax,WA 12,01J,Hilliard Airpark,Hilliard,FL Output file name is input name + ".json" extension. Sample JSON output: [ { "pk": 1, "model": "app_airport.Airport", "fields": { "name": "Animas Air Park", "city": "Durango", "ident": "00C", "state": "CO", } } ] **Debugging Conversion Problems** If JSON import errors out with "ValidationError: This value must be an integer", you probably have a blank in an Integer field within your CSV file, but if can't figure out, try setting a breakpoint in file: ./django/django/db/models/fields/__init__.py e.g. 688 try: 689 return int(value) 690 except (TypeError, ValueError): 691 import pdb; pdb.set_trace() 692 -> raise exceptions.ValidationError( 693 _("This value must be an integer.")) To figure out what field caused the error, while in the debugger: (Pdb) u <- to go UP the callstack (Pdb) field.name

  • json
  • loaddata
  • fixtures
  • csv
  • import
  • fixture
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

OracleAuthBackend

This code uses oracle as an authentication back end. It creates a new connection to the db and attempts to login. If successful it will then create an upper case User account with _ORACLE appended to the username. My urls.py call: from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}), ) My setting.py specific settings: AUTHENTICATION_BACKENDS = ( 'oracleauth.views.OracleAuthBackend', ) LOGIN_URL = '/accounts/login/' ORACLE_CONNECT = 'database-host:1521/database' DEBUG=True

  • authentication
  • oracle
  • login
  • auth
  • backend
Read More

EmailListField for Django

A simple Django form field which validates a list of emails. [See this at my blog](http://sciyoshi.com/blog/2009/aug/08/emaillistfield-django/)

  • fields
  • forms
  • email
  • form
  • field
  • email-list
Read More

Redirect view based on GEO

Wanted a neat way to redirect views based on GeoIP determined criteria, from HTTP_REFERER. Decorator approach seemed the best way to make it straightforward to redirect views. To use, installed the Max Mind Python GeoIP API : http://www.maxmind.com/app/python

  • view
  • redirect
  • geoip
Read More

Manager for multiple database connections

A Django model manager capable of using different database connections. Inspired by: * [Eric Florenzano](http://www.eflorenzano.com/blog/post/easy-multi-database-support-django/) * [Kenneth Falck](http://kfalck.net/2009/07/01/multiple-databases-and-sharding-with-django) There's a more detailed version in Portuguese in my blog: [Manager para diferentes conexões de banco no Django](http://ricobl.wordpress.com/2009/08/06/manager-para-diferentes-conexoes-de-banco-no-django/)

  • multiple
  • manager
  • database
  • connection
  • databases
  • connections
Read More
Author: rix
  • 0
  • 6

UsernameField (for clean error messages)

This is a username field that matches (and slightly tightens) the constraints on usernames in Django's `User` model. Most people use RegexField, which is totally fine -- but it can't provide the fine-grained and user friendly messages that come from this field.

  • fields
  • forms
  • user
  • auth
  • form
  • field
  • username
  • users
  • authorization
Read More

SQL Log To Console Middleware

When running the Django development server, this middleware causes all executed SQL queries to get printed out to the console. This is based on [Snippet 161](http://www.djangosnippets.org/snippets/161/). The big difference is that 161 logs by adding stuff to your response text, which isn't very convenient IMO.

  • sql
  • middleware
  • log
  • debug
  • logging
  • console
Read More

2956 snippets posted so far.