Login

All snippets

Snippet List

MaxMind(R) GeoIP Lite CSV Import

Use this script to import the Maxmind GeoIP lite CSV datasets into your database. This takes at least 200MB of RAM; the resulting database will be ~400MB. Stick in the same directory as the [models](http://www.djangosnippets.org/snippets/327/). Make sure to set `DEBUG=False` to prevent running out of memory during import.

  • log
  • csv
  • gis
  • ip
  • geolocation
  • maxmind
  • geodjango
  • import
Read More

MaxMind(R) GeoIP Lite geolocation models

This provides GeoDjango models for the maxmind GeoIP Lite data products. Use the corresponding [CSV import script](http://www.djangosnippets.org/snippets/328/) for data import. Requires: [GeoDjango](http://code.djangoproject.com/wiki/GeoDjango) and the [BigIntegerField patch](http://code.djangoproject.com/attachment/ticket/399/django-bigint-20070712.patch) by Peter Nixon.

  • log
  • gis
  • ip
  • geolocation
  • maxmind
  • geodjango
Read More

Cheetah-style comments

For those who find the Django comments syntax tedious, this snippet enables the use of (almost) Cheetah-style comments.

  • template
  • comments
  • cheetah
Read More

"Approved" field with timestamp

I wanted to make the objects of a particular model approvable and store the timestamp of when that happened. In other frameworks/languages, I used to combined those in one "approved_at" field, which would be NULL if an object was currently unapproved. I tried different approaches to implement this in django, and this is the best I came up with so far. Basically, the code in __setattr__ makes sure that the field, once set, will not be updated again. Overriding setattr__() could also be a solution to determining if a field value has changed in save(), a question that seems come up from time to time in #django.

  • newforms
  • models
  • fields
  • forms
  • save
Read More

DefaultValueWidget

Can be used if a form field should not be editable, but the current value or the value that will be automatically used should still be visible to the user. __init__ takes two additional parameters: **value** is the actual value to be used when saving the form, while **display** determines what is shown to the user when rendering. If *display* is not specified, *value* itself will be used instead. If *display* is a *ModelChoiceField*, *value* is assumed to be a primary key of the model, and the widget will automatically try to retrieve and use the string representation of the corresponding item.

  • newforms
  • forms
  • widgets
  • widget
Read More

instant 'master' admin site

The newforms-admin branch (to be merged by 0.97, I think) is very nice to work with, separating models from the admin. It is trivial to create an admin site that includes every app that is installed. Note that you also get all your docs for things like template tags, etc.

  • admin
  • newforms-admin
Read More

BabelMiddleware

Originally posted on [skam.webfactional.com](http://skam.webfactional.com/blog/2007/07/16/babel-integration-django/) This is a very simple middleware that uses babel (http://babel.edgewall.org) for accessing locale data in request objects through request.LOCALE attribute. It also provides a function to get locale data outside views. settings.py: MIDDLEWARE_CLASSES = ( ... cut ... 'django.middleware.locale.LocaleMiddleware', 'middleware.locale.BabelMiddleware', ... cut ... )

  • middleware
  • i18n
  • l10n
  • locale
  • babel
Read More

Flash Message Template Tag

Flash message add-on for Django. Uses sessions. Behavior is such that you set a flash message in a view. That message is stored in the sesssion. Then whenever it is that the message gets displayed, it is removed from the session (never to be heard from again) **Installation:** In your settings, enable the following items. TEMPLATE_CONTEXT_PROCESSORS django.core.context_processors.request MIDDLEWARE_CLASSES django.contrib.sessions.middleware.SessionMiddleware Then put it into a file called flash.py in your templatetags directory. **Usage:** It's pretty simple. Do something like this in your view .. >>>request.session['flash_msg'] = 'Your changes have been save' >>>request.session['flash_params'] = {'type': 'success'} And maybe put something like this in your template {% load flash %} {% flash %} <h2>{{ params.type }}</h2> {{ msg }} {% endflash %} It also support a flash template, you can specify a file FLASH_TEMPLATE in your settings file and then that file will be rendered with msg and params as available variable. Usage for this would simply be `{% flash_template %}` and then you gotta make a template file that does whatever you like. Outside of that just be aware you need the Django session middleware and request context installed in your app to use this.

  • template
  • flash
  • message
Read More

Random code tag

This tag solves for me a simple need: generate random and compact codes for some of my applications. Codes are not guaranteed to be unique. **Usage** {% randomCode "num" %} **Example**: {% randomCode "8" %} generates a random 8 characters code. Create a file on your favorite template tags folder called randomcode.py and paste the code. Don't forget to include {% load randomcode %} in your templates

  • tag
Read More

DRY with common model fields

If you have many models that all share the same fields, this might be an option. Please note that order matters: Your model need to inherit from TimestampedModelBase first, and models.Model second. The fields are added directly to each model, e.g. while they will be duplicated on the database level, you only have to define them once in your python code. Not sure if there is a way to automate the call to TimestampedModelInit(). Tested with trunk rev. 5699. There is probably a slight chance that future revisions might break this.

  • models
  • model
  • inheritance
Read More

Hidden Forms

Have your forms descend from this BaseForm if you need to be able to render a valid form as hidden fields for re-submission, e.g. when showing a preview of something generated based on the form's contents. Custom form example: >>> from django import newforms as forms >>> class MyForm(HiddenBaseForm, forms.Form): ... some_field = forms.CharField() ... >>> f = MyForm({'some_field': 'test'}) >>> f.as_hidden() u'<input type="hidden" name="some_field" value="test" id="id_some_field" />' With `form_for_model`: SomeForm = forms.form_for_model(MyModel, form=HiddenBaseForm)

  • newforms
  • form
  • baseform
  • hidden
Read More

Binding pre-existing tables with dynamically created class models

This snippet proposes a solution for pre-exisiting database tables that have no counterpart in your django application models.py module. My use case was a comercial systems where pricing tables were created on-the-fly as a result of a stored procedure's execution inside the database. These pricing tables had no counterpart class model. Therefore, to access these tables from Python code you had to bypass Django's ORM and use plain-old SQL through cursos.execute(). This snippet's strategy is to create a (model) class on the fly and inject that class inside models.py namespace. After that you can use the generated class and Django's ORM machinery to access the tables, as if they were created by syncdb.

  • orm
  • dynamic-model
Read More

3110 snippets posted so far.