Login

3110 snippets

Snippet List

Git media cache busting tag

This tag appends the current git revision as a GET parameter to a media files so the web server can set an expires header far in the future. Your project must be structured such that MEDIA_ROOT/../.git exists. Usage: `<link rel="stylesheet" type="text/css" href="{% media myapp/css/base.css %}">`

  • cache
  • media
  • git
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

Middleware to move tags <script> to the bottom

This middleware makes the page load faster because it moves all tags <script> to the end of document. When a tag <script> loads, it blocks parallel loading, so, the best practice is load them after load CSS and images. To use it, just put in a file and add to your setting MIDDLEWARE_CLASSES.

  • performance
  • script
  • otimization
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

Firebug Lite Middleware

This middleware allows you to easily include the excellent debugging tool Firebug Lite in your projects. To install it, just add the middleware class to your list of installed middleware, pretty much anywhere in the list. If DEBUG is True, and your IP address is in the list of INTERNAL_IPS, Firebug Lite will load. It will, however, only load in browsers that are **not** Firefox, as I'm assuming that you have the **real** Firebug installed in Firefox. If you don't, go install it--what's wrong with you? Check out http://getfirebug.com/lite.html for more information.

  • middleware
  • debug
  • ie
  • debugging
  • firebug
  • msie
Read More
Author: jfw
  • 8
  • 15

Admob Ad Insertion Snippet

**Update**: [Django AdMob](http://github.com/johnboxall/django_admob/tree/master) pluggable app on github. Given a Django ``request`` object and dict of admob parameters returns a Admob ad. If no ad can be retrieved displays a one pixel Admob tracker image. For the future: * Make a template tag for this? * Filter out other unneeded META parameters for the admob_post dict?

  • admob
  • ad
  • ads
  • mobile
Read More

minimal nginx conf to split get/post requests

After a point the sql server becomes the bottleneck in lots of web application, and to scale, master-slave replication with single master, multiple slave is recommended. This setup with nginx can be used to accomplish traffic distribution between master and slave based on request method.

  • middleware
  • nginx
  • loadbalancing
  • master-slave
Read More

LoginRequired class-based view decorator

Apply the `login_required` decorator to all the handlers in a class-based view that delegate to `cls.dispatch`. Optional arguments: * redirect_field_name = `REDIRECT_FIELD_NAME` * login_url = `None` See the documentation for the [`login_required`](https://docs.djangoproject.com/en/dev/topics/auth/#the-login-required-decorator) method for more information about the keyword arguments. Usage: @LoginRequired class MyListView (ListView): ...

  • view
  • decorator
  • class
  • login_required
  • class-decorator
  • class-based-views
Read More

Return to change_list with filter after change

This snippet allows you to return back to the filtered change_list after clicking "Save" on a change form. Other snippets I've found don't seem to take into account clicking on "Save and add another" or "Save and continue"

  • filter
  • admin
  • change_list
Read More

Private Context Decorator

Django's standard inclusion_tag doesn't include context variables by default. When you add takes_context you are required to manually merge the context variables into the dict which your tag returns, which tends to result in wasteful code or [possibly accidentally] leaking variables into the global context (`context.update({…})`). This decorator allows your inclusion tag to remain simple and still have safe access to the global context for things like `MEDIA_URL`: @register.inclusion_tag('my_template') @private_context def my_tag(context, …): return {"foo": 1, "bar": 2}

  • templatetag
  • decorator
  • context
  • inclusion_tag
Read More

iTunes Podcast RSS Feed

The syndication documentation gives a very basic beginning to creating an iTunes Podcast Feed, but leaves a lot of work left to be figured out. This is a completed example. Because I needed to obtain the duration of the podcast file programmatically (not part of this code) I limit the podcast to mp3 files. If you want to obtain durations some other way you can set the mime_type in the same manner as the other properties. This is what I'm using and should be plenty for you to customize from.

  • feed
  • rss
  • syndication
  • iTunes
  • podcast
Read More

Front end admin toolbar

This snippet will monkeypatch `django.db.models.Model` to include 7 new methods: * `get_verbose_name` Because you can't access model._meta from templates * `get_verbose_name_plural` * `get_admin_change_url` * `get_admin_delete_url` * `get_admin_history_url` * `get_admin_changelist_url` * `get_admin_add_url` This snippet also gives you the template code to paste to your `base.html` so every front end model instance view of your site will show an admin toolbar for logged in users that have admin access.

  • admin
  • toolbar
Read More

Dynamic Regroup Template Tag

Django's built-in {% regroup %} template tag is great, but sometimes, you need to pass in the attribute you want to group on instead of declaring the attribute when you define the tag. {% dynamic_regroup %} is identical in function to {% regroup %}, except that it will attempt to resolve a context variable for the attribute you want to group by. {% dynamic regroup %} is also backward compatible, so you can also hand in the attribute literal and it will work as expected. See the end of the code for an example of usage.

  • templatetag
  • dynamic
  • regroup
Read More

Read only form & model field

These decorators can be used to make some model/form fields readonly. **Sample usage:** # Use this decorator on form with readonly fields.` @modelform_with_readonly_fields` class FooAdminForm(forms.ModelForm):` ... # This decorator shoud be used to protect selected fields ` # from modification after initial save.` @has_readonly_fields` class Foo(models.Model):` read_only_fields = ('name', )` ... **Result** will be the same as shown in this post: [Readonly field](http://stackoverflow.com/questions/324477/in-a-django-form-how-to-make-a-field-readonly-or-disabled-so-that-it-cannot-be/1424453#1424453) and [Readonly model field](http://www.djangozen.com/blog/read-only-fields-in-models)

  • forms
  • model
  • field
  • readonly
Read More