Login

Most bookmarked snippets

Snippet List

RangeField and RangeWidget

These field and widget are util for to those fields where you can put a star and end values. It supports most of field types and widgets (tested with IntegerField, CharField and DateField / TextInput and a customized DateInput). **Example of use:** class FormSearch(forms.Form): q = forms.CharField(max_length=50, label=_('Search for')) price_range = RangeField(forms.IntegerField, required=False) **Example of use (with forced widget):** class FormSearch(forms.Form): q = forms.CharField(max_length=50, label=_('Search for')) price_range = RangeField(forms.IntegerField, widget=MyWidget)

  • forms
  • field
  • widget
  • range
Read More

Admin Hack: Quick lookup of GenericForeignKey id by ContentType

Generic Relations with django.contrib.contenttypes.generic.GenericForeignKey work well for models but the admin interface just shows the object id as an integer with no easy way to lookup the id of a new object. This jquery javascript adds a "Lookup <ContentType Name>" link next to the object id field in the admin interface. This is done by reusing the showRelatedObjectLookupPopup() function provided with django which is used when the field is included in raw_id_fields (a little magnifying glass linked to popup object selector shows up). This essentially works the same way but changes which model's objects are shown and selected in the popup based on the ContentType selected for object_type

  • javascript
  • admin
  • jquery
  • genericforeignkey
  • lookup
  • contenttype
  • object_id
  • raw_id
  • popup
Read More

collectmedia command: Copy or link media files from installed apps

This management command discovers media files from all `INSTALLED_APPS` (or the apps you specify) and copies or links them to `MEDIA_ROOT`. Put this code in a file like so: yourapp/management/commands/collectmedia.py ...and don't forget the necessary `__init__.py` files. This command includes an interactive mode (`-i` or `--interactive`) and a dry run mode (`-n` or `--dry-run`) for previewing what will happen. See `manage.py help collectmedia` for more options.

  • media
  • management
  • command
Read More

Jinja2 Django integration

Integration of django and Jinja2. Just import render_to_response from this file and you are ready. This file automatically adds template search path from yout TEMPLATE_DIRS and from each installed application. You can also use several variables in your settings.py to add filters, tests and global functions to the default context. This can be done by using JINJA_GLOBALS, JINJA_FILTERS and JINJA_TEST e.g. `JINJA_FILTERS = ( 'myapp.filters.myfilter', 'myapp.filters.myfilter2', )`

  • templates
  • jinja
  • jinja2
Read More

Retrieve a list of countries from GeoNames

GeoNames provides a useful data file with information about every country in the world (DjangoPeople uses this). Here's an importer that grabs the file from the web and turns it in to a list of dictionaries.

  • countries
  • geonames
Read More

Model dependency graph using graphviz (script)

Instructions: Set your environment variables, install graphviz, and run. Finds all models in your installed apps and makes a handsome graph of your their dependencies based on foreignkey relationships. Django models have green outlines, yours have purple. The edge styling could be changed based on edge type.

  • models
  • graph
  • graphviz
Read More

twitter_status

Ah simple_tag for get last update of twitter. How twitter limit the fetch rss so, add cache tag for each 30min ( 60*30) update the twitter. if.

  • template
  • simple_tag
  • twitter
Read More

Replace model select widget in admin with a readonly link to the related object

This replaces the html select box for a foreign key field with a link to that object's own admin page. The foreign key field (obviously) is readonly. This is shamelessly based upon the [Readonly admin fields](http://www.djangosnippets.org/snippets/937/) snippet. However, that snippet didn't work for me with ForeignKey fields. from foo.bar import ModelLinkAdminFields class MyModelAdmin(ModelLinkAdminFields, admin.ModelAdmin): modellink = ('field1', 'field2',)

  • admin
  • field
  • widget
  • readonly
  • modelchoicefield
Read More

Manager method for limiting GenericForeignKey queries

This is a simple manager that offers one additional method called `relate`, which fetches generic foreign keys (as referenced by `content_type` and `object_id` fields) without requiring one additional query for each contained element. Basically, when working with generic foreign keys (and esp. in the usecase of having something like a tumblelog where you use an additional model just to have a single sorting point of multiple other models), don't do something like `result = StreamItem.objects.select_related()` but just fetch the content type with `result = StreamItem.objects.select_related('content_type')`, otherwise you will end up with first one query for the list of StreamItems but then also with one additional query for each item contained in this resultset. When you now combine the latter call with `result = StreamItem.gfkmanager.relate(result)`, you will just get the one query for the item list + one query for each content type contained in this list (if the models have already been cached). For further details, please read [this post](http://zerokspot.com/weblog/2008/08/13/genericforeignkeys-with-less-queries/) on my blog.

  • foreignkey
  • generic
  • manager
  • query
  • tuning
Read More

[UPDATE]Filter to resize a ImageField on demand

A filter to resize a ImageField on demand, a use case could be: <img src="{{ object.image.url }}" alt="original image"> <img src="{{ object.image|thumbnail }}" alt="image resized to default 104x104 format"> <img src="{{ object.image|thumbnail:200x300 }}" alt="image resized to 200x300"> Original http://www.djangosnippets.org/snippets/192/

  • template
  • image
  • thumbnail
Read More

Multiple-Submit-Button Widget for Choice Field

Django administration provides three buttons for submitting the currently edited object. Each of them has a unique name and depending on the name that is sent to the server, the specific action is performed. I see this as an ugly solution and prefer to have a choice field in the form which would render as submit buttons with different values. Then the values would be checked instead of the names. Therefore, I created the `MultipleSubmitButton` widget. When `<input type="submit" value="Go" />` is used, the value sent to the server always matches the text on the button, but if `<button type="submit" value="go">Go</button>`, the value and the human representation might differ. To use the `MultipleSubmitButton` widget, pass it to the widget parameter of a `ChoiceField` like this: SUBMIT_CHOICES = ( ('save', _("Save")), ('save-add', _("Save and Add Another")), ) class TestForm(forms.Form): do = forms.ChoiceField( widget=MultipleSubmitButton, choices=SUBMIT_CHOICES, ) When you print `{{ form.do }}` in the template, the following HTML will be rendered: <ul> <li><button type="submit" name="do" value="save">Save</button></li> <li><button type="submit" name="do" value="save-add">Save and Add Another</button></li> </ul> When you submit this form and check the validity of it, `form.cleaned_data['do']` will return "save" or "save-add" depending on the submit button clicked.

  • forms
  • widget
  • submit
Read More

Authentication Against Active Directory (LDAP) over SSL

I had some trouble getting other peoples code to work for AD support, so I wrote my own which authenticates against LDAP and will also use SSL and cert if required. It will also verify that an autheticated user has specific group membership before authorizing. This will also debug to a file, which is really helpful when trying to figure out problems. One thing that really got me when getting python-ldap to work was that you must have "ldap.set_option(ldap.OPT_REFERRALS,0)" set or any ldap search will not work. Also, this will add group permissions to a user.

  • authentication
  • ssl
  • ldap
  • active-directory
Read More

Custom color field with Javascript color picker

A custom model field 'ColorField' which stores a hex color value like '#FFFFFF' and shows a Javascript color picker in the admin rather than a raw text field. It is written to work with the current trunk (i.e. after newforms-admin merge). You'll need the ColorPicker2.js file found at [www.mattkruse.com](http://www.mattkruse.com/javascript/colorpicker/combined_compact_source.html) (his license prohibits including the file here). This should be placed in the 'js' folder of your admin media. The snippet includes a python source file which can be placed wherever you wish, and a template which by default should be placed in a folder 'widget' somewhere on your template path. You can put it elsewhere, just update the path ColorWidget.render The custom field at present does not validate that the text is a valid hex color value, that'd be a nice addition.

  • newforms
  • javascript
  • models
  • admin
Read More

Enumeration field

These three classes allows you to use enumerations (choices) in more natural model-like style. You haven't to use any magic numbers to set/get field value. And if you would like to make your enumeration a full-fledged django-model, migration should be easy. Note, that you can subclass Item to add some context-specific attributes to it, such as `get_absolute_url()` method for instance. Examples are provided in the form of `doctest` in the second half of the snippet.

  • newforms
  • choice
  • model
  • field
Read More

3110 snippets posted so far.