Login

Top-rated snippets

Snippet List

Sorl thumbs for the lazy

Sorl thumbs for the lazy. **Usage:** {% thumb p.image "noimage.png" %} *tags.py* goes into your templatetags directory. *includes/thumb.html* goes into your templates directory. [Fork it here.](https://gist.github.com/985439)

  • sorl-thumbnail
Read More

HTML5 filter for XXS

Usefull for TinyMCE, to allow some HTML but be vunarable by XXS attacks You need to install html5lib sudo easy_install html5lib

  • template
  • filter
  • security
  • sanitize
  • xss
Read More

Model Locking Mixin & Decorator (MySQL Advisory Locks)

This code provides a mixin and decorator which, when used together, can provide advisory locking on model methods. It provides locking by using MySQL's advisory lock system. See the example at the bottom of the code. This is a convenient and easy way to guarantee your model methods have exclusive access to a model instance. The LockableObjects class requires a MySQL backend, but it could be modified to use other back-end locking systems. The lock name generation in `LockableObject.get_lock_name()` could be altered to create much more complex locking schemes. Locking per-object, per-method for example.. Lock attempts have a timeout value of 45 seconds by default. If a timeout occurs, EnvironmentError is raised. **See the bottom of the script for an example** > **Instructions:** * **1:** Place the code in locking.py somewhere in your path * **2:** In your models.py (or any script with an object you want to lock): `from locking import LockableObject, require_object_lock` * **3:** In the model you want locking for, add the `LockableObject` mixin * **4:** Decorate the method you want to be exclusively locked with `@require_object_lock`

  • model
  • mysql
  • decorator
  • mixin
  • locking
Read More
Author: pio
  • 0
  • 2

models ColorField with clean minimal widget

A simple model ColorField that allows picking from a predefined list (currently picked up from settings.py The widget displays as a row of coloured SPAN's with the hex code inside. Simply click to choose a color. (requires jQuery in the page assigned to it's normal $ shortcut. Easy to change this is you don't use jQuery in this way)

  • models
  • admin
  • jquery
  • widget
  • custom-field
  • modelfield
Read More

When saving in admin it will call model save() twice.

When I save this in admin, it will call model save() twice Django version 1.2.3, using settings 'admin.development' Development server is running at http://127.0.0.1:8080/ Quit the server with CONTROL-C. [18/May/2011 10:08:22] "GET /admin/onixcodes/bookbatch/ HTTP/1.1" 200 38211 [18/May/2011 10:08:22] "GET /admin/jsi18n/ HTTP/1.1" 200 4256 [18/May/2011 10:08:29] "GET /admin/onixcodes/bookbatch/55/ HTTP/1.1" 200 9811 [18/May/2011 10:08:29] "GET /admin/jsi18n/ HTTP/1.1" 200 4256 save!! save!! [18/May/2011 10:08:33] "POST /admin/onixcodes/bookbatch/55/ HTTP/1.1" 302 0 [18/May/2011 10:08:33] "GET /admin/onixcodes/bookbatch/ HTTP/1.1" 200 38364 [18/May/2011 10:08:33] "GET /admin/jsi18n/ HTTP/1.1" 200 4256 Anyone has any suggestion? Thanks.

  • admin
  • save()
  • twice
Read More

ad-hoc request authentication

This is auth_data_required decorator analogous to login_required where authentication data must come in POST of request. It's useful for API. I took the idea from [Tumblr API](http://www.tumblr.com/docs/en/api).

  • authentication
Read More

Field List Tag

Tag for iterating through the fields of an object from a template. The tag is passed two string arguments, the name of the model to use (which is then looked up in the context dictionary), and the format string. The format string should include two string place holders. The tag will output each field name and value according to the format string supplied.

  • properties
  • field
  • iterate
Read More

CollectionFrom (GeometryCollection <-> Geometry Fields!)

Motivation: We can't use GeometryCollections to do filters, etc in GeoDjango due to incomplete underlying libraries. But with this CollectionFrom field we can get all the benefits of working with GeometryCollections but still query based on points, lines, polys. If you're using GeometryCollectionFields and see this error: DatabaseError: Relate Operation called with a LWGEOMCOLLECTION type. This is unsupported. Then this will probably be helpful for you.

  • geodjango
  • geo
  • geometrycollection
Read More

Default URL handler

Default URL handler allows views to be loaded without defining them in the urls.py. Views will therefore be loaded based on the pattern of the browser url. For example http://host/app_name/view_name will load project_name.app_name.views.view_name. Though I would not used this in production, it can be used to speed-up development.

  • url
Read More

Simple template tag to do |stringformat filter with format from a variable

Formats a django variable using a python string formatting as specified in another template variable. Similar to |stringformat. Takes two arguments: the django template variable with the item to be formatted and the django template variable containing the format string. {% pyformat number formatstringvar %} Place this file in `appname/templatetags/pyformat.py` and you're good.

  • template-tag
  • string-formatting
Read More

Plaintext format (advanced spaceless)

A template loader useful for writing templates with carefully controlled newlines and spaces while retaining readable template source code formatting. Start the template with PTFTAG (`{#ptfable#}`, here) to allow it to be processed. Common problems with doing it to most templates as-is is use of newlines to separate words and multiple spaces between tags where spaces are still needed (which is problematic with `spaceless` tag as well). Currently intended as a template loader wrapper, and is suggested to be used with cached loader. Example settings.py configuration: _lp = lambda lo, *ar: (lo, ar,) # loader, arguments TEMPLATE_LOADERS = ( _lp('django.template.loaders.cached.Loader', # cache _lp('ptf.template.ptftemplateloader.Loader', # ptf 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', #'django.template.loaders.eggs.load_template_source' ), # ptf ), # cache ) (change `ptf.` to wherever in python path you've put it). You might also need couple of simple template tags for explicitly inserting newlines or whitespaces: def br(): return "\n" br = register.simple_tag(br) # XHTML-XMPP-template compatible. def brx(): return "<br />\n" brx = register.simple_tag(br) def ws(): return " " ws = register.simple_tag(ws) .

  • spaceless
  • ptf
Read More

Human readable file names decorator

This is extremely simple decorator to add possibility to upload files with name specific in some object field. For example image with same name as object slug. Sample **model**: class Test(models.Model): image = models.ImageField(\ upload_to=upload_to_dest(path='pics/', \ human_readable_field='hrname')) hrname = models.CharField( \ max_length=128, \ blank=True, default='') Sample **form** for admin: FNAME_EXP = re.compile('^[A-Za-z0-9\-\_]+$') class TestAdminForm(forms.ModelForm): hrname = forms.RegexField( label="Human Readable File Name", \ regex=FNAME_EXP, \ help_text="""Allowed only latin alphabet (upper and lower cases), underscore and minus characters. PLEASE, DO NOT INCLUDE EXTENSION OF THE FILE. Sample: test-this-file""", \ required=False) class Meta: model = Test Sample *admin.py* for *Test* model: class TestAdmin(admin.ModelAdmin): form = TestAdminForm admin.site.register(Test, TesetAdmin)

  • django
  • ImageField
  • file uploads
  • file name
  • FileField
Read More

remove the annoying "Hold down control..." messages

This function mangles a generated form class to remove the Hold down "Control", or "Command"... messages from the help text. This is really a dirty hack awaiting a proper solution to [Django ticket 9321](http://code.djangoproject.com/ticket/9321). This function can be useful for forms in the admin interface that use custom widgets. Basic usage: class MyModelForm(forms.ModelForm): class Meta: model = MyModel class MyAdmin(admin.ModelAdmin): form = remove_holddown(MyModelForm, ('field1', 'field2'))

  • admin
  • forms
  • hack
  • widget
Read More

3110 snippets posted so far.