Login

All snippets written in Python

2956 snippets

Snippet List

Switch/case conditional tags

This tag allow you to use C-like switch tag in your templates. It is useful for sequencial and repetitive `{% ifequal %}` tags. To install it in your project, you just need to follow [these instructions](http://www.djangoproject.com/documentation/templates_python/#extending-the-template-system)

  • tag
  • conditional
  • switch
  • case
Read More

Owner required decorator

This decorator allows edit or delete for the owner of the record. Snippet applies for every model that has ForeignKey to User. Works for User model too. Works with other decorators as permission_required or similar. Decorator raise http 403 view if user is not owner. **Usage** @permission_required('blogs.change_entry') @owner_required(Entry) def manage_entry(request, object_id=None, object=None): Decorator populates object kwargs if object_id present, otherwise just returns original view function. @permission_required('blogs.delete_entry') @owner_required() def entry_delete(*args, **kwargs): kwargs["post_delete_redirect"] = reverse('manage_blogs') return delete_object(*args, **kwargs) In generic delete wrapper view returns original view function.

  • decorator
Read More

YouTube Template Filter

Given a youtube url (can copy and paste right from the browser) turns the url into an embedded video. If you put this in your app's templatetags/filters.py, you can do the following >{{ object.youtube_url|youtube }} and it would embed the youtube video.

  • template
  • filter
  • youtube
  • embed
Read More

(en-US) Humanized Decimal Field

Simple DecimalField class extension that automatically adds formatting and validation for comma-separated "decimals". Works wonderfully for price fields. Could be extended to strip dollar signs or to be locale-agnostic.

  • form
  • humanize
  • field
  • comma
  • decimal
  • thousands
  • separator
  • input
Read More

ActiveManager: filter objects depending on publication and/or expiration dates

This manager is intended for use with models with publication and/or expiration dates. Objects will be retrieved only if their publication and/or expiration dates are within the current date. Use is very simple: class ExampleModel(models.Model): publish_date = models.DateTimeField() expire_date = models.DateTimeField(blank=True, null=True) objects = models.Manager() actives = ActiveManager(from_date='publish_date', to_date='expire_date') ExampleModel.actives.all() # retrieve active objects according to the current date The manager works correctly with nullable date fields. A null publication date means "*always published (until expiration date)*" and a null expiration date means "*never expires*". Most models should define the `objects` manager as the default manager, because otherwise out of date objects won't appear in the admin app.

  • model
  • manager
  • active
  • publication
  • expiration
  • date-filter
Read More

SectionedForm

Sometimes we need divide forms in fieldsets, but this make us declare all fields in HTML template manually. This class is to help you to do this by a easy way. **How to use** First, download this file as name "sectioned_form.py" Later, turn your form inherited from the class **SectionedForm**, override method "_html_output" and declare fieldsets and fieldset_template attribute, like below: from sectioned_form import SectionedForm class MyForm(forms.ModelForm, SectionedForm): fieldsets = ( (None, ('name','age','date')), (_('Documents'), ('number','doc_id')), ) fieldset_template = "<h2>%s</h2>" def _html_output(self, *args, **kwargs): return SectionedForm._html_output(self, *args, **kwargs)

  • newforms
  • forms
  • form
  • formset
Read More

Timing Django Requests

Adds an 'X-Django-Request-Time' HTTP response header that times how long django spent processing the request.

  • middleware
  • http
  • headers
  • profiling
Read More

Django newforms ExtJS JSON Encoder

This is a subclass of Django's built-in JSONEncoder that adds the ability to output form and field objects as ExtJS-compatible config objects. Simple example: from django.utils import simplejson json = { 'data': [], 'success': True, 'metaData': { 'fields': SFY09RDOForm(), 'root': 'data', 'successProperty': 'success' }, } return HttpResponse(simplejson.dumps(json, cls=ExtJSONEncoder)) Where SFY09RDOForm is a subclass of django.forms.Form. 6/20/2008: Updated to pass on the help_text parameter (useful in combination with this override in ext: http://extjs.com/forum/showthread.php?t=36642)

  • json
  • ext
  • encoder
  • extjs
Read More

RandomFileExtensionMiddleware

If you feel nostalgic for the old days of crufty URLs, put this middleware somewhere in your Django app and add the first entry in settings.MIDDLEWARE_CLASSES as shown below. Keep in mind that you need to replace 'path.to' with the correct Python path to the middleware. MIDDLEWARE_CLASSES = ( 'path.to.RandomFileExtensionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ) Note: Although this works it's still a joke.

  • middleware
Read More

Adding buttons to submit line in a Admin page

**Attention: this snippet depends on jQuery library to works** The Admin templates hierarchy does not allow you change the submit line (that buttons bar in the footer of the change view of a model class). This code shows how to resolve this, using a simple javascript trick. You can read the code and implement using your favorite javascript library (instead of jQuery) or pure JavaScript. This example regards to User Profile, a common used model class that adds custom fields to a user in the authentication system. To use this, you must put this template code in a file with the following name: templates/admin/auth/user/change_form.html

  • template
  • ajax
  • javascript
  • admin
  • query
Read More

Generating Taconite command documents

Hello, This is a port of a php class used to generate XML taconite command documents, useful for (very) easy and powerful ajaxy stuff, if you don't know what that is just check it there in french : http://www.desfrenes.com/playground/taconite/ or there in english : http://www.malsup.com/jquery/taconite/. Basically what it does is generate an XML document that is later processed by a javascript plugin which executes a serie of DOM modifications. About the code, I'm a Django beginner as well as a Python beginner so kind advices are welcome. Cheers.

  • ajax
  • django
  • javascript
  • python
  • jquery
  • taconite
  • minidom
  • dom
Read More

Variable inspect filter

This module has two template filters allowing you to dump any template variable. Special handling for object instances. Pretty output. Usage: {% load dumper %} ... <pre>{{ var|rawdump }}</pre> or {% load dumper %} ... {{ var2|dump }} How to install: As usual, put into `<your-proj>/<any-app>/templatetags/dumper.py`.

  • template
  • filter
  • dump
  • variable
  • inspect
Read More

YUI Loader as Django middleware

This server-side middleware implements some of the functionality in the Yahoo User Interface Loader component. YUI JavaScript and CSS modules requirements can be declared anywhere in the base, inherited or included templates, and the resulting, optimized `<script>` and `<link rel="stylesheet">` tags are inserted at the specified position of the resulting page. Requirements may be specified in multiple locations. This is useful when zero or more components are included in the HTML head section, and inherited and/or included templates require possibly overlapping sets of YUI components in the body across inherited and included templates. All tags are collected in the head section, and duplicate tags are automatically eliminated. The middleware understands component dependencies and ensures that resources are loaded in the right order. It knows about built-in rollup files that ship with YUI. By automatically using rolled-up files, the number of HTTP requests is reduced. The default syntax looks like HTML comments. Markup for the insertion point is replaced with `<script>` and `<link>` tags: <!-- YUI_init --> Component requirements are indicated, possibly in multiple locations, with the `YUI_include` markup. It is removed from the resulting page by the middleware. Example: <!-- YUI_include fonts grids event dragdrop --> Non-minified and compressed versions are requested, respectively, by: <!-- YUI_version raw --> <!-- YUI_version debug --> Example: <html><head> <!-- YUI_init --> <!-- YUI_include dom event --> </head><body> <!-- YUI_include element selector reset fonts base --> </body></html> Renders: <html><head> <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.1/build/reset-fonts/reset-fonts.css" /> <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.1/build/base/base-min.css" /> <script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/yahoo-dom-event/yahoo-dom-event.js"></script> <script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/element/element-beta-min.js"></script> <script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/selector/selector-beta-min.js"></script> </head><body> </body></html> The markup format can be customized with global Django settings. Example: YUI_INCLUDE_PREFIX_RE = r'{!' YUI_INCLUDE_SUFFIX_RE = r'!}' would change markup to e.g. `{! init !}` and `{! include dom event !}`. The base URL is customized with the `YUI_INCLUDE_BASE` setting, e.g.: YUI_INCLUDE_BASE = 'http://localhost:8000/yui/build/' To remove the XHTML trailing slash from the `<link>` tag, use: YUI_INCLUDE_CSS_TAG = '<link rel="stylesheet" type="text/css" href="%s">' See also the [home page for this module](http://trac.ambitone.com/ambidjangolib/wiki/YUI_include).

  • yui
  • loader
Read More

Image Standarization

Standarization of image fields (for being used when saving models). Automatically creates thumbnail. Change image name to /path/to/images/<my_field>-<id>.<ext>. Resize image and thumbnail to specified size (optionally can crop image to force size).

  • image
  • thumbnail
  • resize
  • rename
Read More