Login

All snippets written in Python

2956 snippets

Snippet List

Image gradients on the fly

A Django view to create an image gradient on the fly as a PNG file. The direction, size and colors of the gradient a specified in the filename and extracted by Django in the urls.py. Example usage from CSS: `background: url(/gradient-down-255,255,255-to-0,0,0-70-of-120.png) repeat-x;` creates a 70-pixel vertical gradient as background from white to gray. No static images needed. To modify, nothing but the CSS needs to be edited.

  • image
  • gradient
  • background
Read More

P3P Headers for iframes

This is nothing fancy and hasn't much to do with django itself, I just searched for this information for quite a while and thought it may be useful for others. If you use IE7 (and maybe IE6), it will block cookies in iframes, if the iframes content comes from another server (quite common, I think). The P3P specification lets you declare your privacy settings in a format interpretable by browsers, essentially you can tell IE that you adhere to "don't be evil", and are allowed to handle cookies afterwards. I don't think that makes much sense, but it seems that it is the only way to make IE accept cookies in iframes. I had no idea that django made it that incredibly easy to "patch" the response-header, but it does! :)

  • p3p
  • ie7
  • internet
  • explorer
  • iframe
  • privacy
Read More

Create breakpoints to time code at

Include in your code like this: t=Timer() Then use it like this: t.tick('Some optional description') It will output the time spent between the tick and the previous tick (or inception) and the total time spent since it began tracking time. Can be placed multiple times in a long segment of code. Can be used to break out the amount of time being spent on various parts of your code so you can focus on optimizing those sections.

  • time
  • high-performance
  • profiling
  • timer
  • optimize
Read More

ManyToManyFieldWithDefault

Extension to the normal ManyToManyField to support default values. Build for the following use case: publish_on = ManyToManyFieldWithDefault(Site, verbose_name=_('publish on'), default=Site.objects.get_current) Where with a plain ManyToManyField the default site will not be selected. The ManyToManyFieldWithDefault fixes this by automatically selecting the default value if no other selections are given. When the field also have null=True and Blank=True it will not select the default !

  • field
  • sites
  • manytomanyfield
  • many
  • default
Read More

EditInline for GenericForeignKey

A simple InlineModelAdmin class that enables you to edit models that are bound by the instance via a generic foreign key (`content_type`, `object_id` pair) Use like: class PlacementInlineOptions( generic.GenericTabularInline ): model = Placement extra = 2 ct_field_name = 'target_ct' id_field_name = 'target_id' Can be also found at #4667

  • admin
  • foreignkey
  • generic
  • edit-inline
Read More

Automate unique slug (again)

This takes the "easier to ask forgiveness than permission" approach to making sure your model's slug is unique. If the model's slug is empty, make a slug from the model's 'name' field. We assume that it is a conflicting slug that is throwing the IntegrityError, in which case if the slug does not end with '-' followed by a number then append '-2'. If the slug does end with '-' followed by a number then capture that final number, increment it by one, save the new slug value and try savin g again.

  • slug
  • save
Read More

DropDownMultiple widget

Observation: depends on jQuery to works! This widget works like other multiple select widgets, but it shows a drop down field for each choice user does, and aways let a blank choice at the end where the user can choose a new, etc. Example using it: class MyForm(forms.ModelForm): categories = forms.Field(widget=DropDownMultiple) def __init__(self, *args, **kwargs): self.base_fields['categories'].widget.choices = Category.objects.values_list('id', 'name') super(MyForm, self).__init__(*args, **kwargs)

  • newforms
  • multiple
  • forms
  • jquery
  • select
  • widget
Read More

hide_email

This templatetag obsfucate mailto link and hide it while not happen onmouseover event. Usage: {% hide_email object.author object.author.email %} Output: <a href="mailto:[email protected]" onmouseover="var a=String.fromCharCode(79+35,14+103,66+41,30+71,49+49,16+81); var b=String.fromCharCode(14+50,9+105,61+56,81+26,92+9,2+96,20+77,13+33,75+24,32+79,31+78); this.href=['mail','to:',a,b].join('');">rukeba</a> Based on [Email Obsfucator](http://www.djangosnippets.org/snippets/536/) and [forums at Yandex.Market](http://market.yandex.ru/forums/). Example at [my guitar blog](http://rukeba.com/ra/2008/01/15/oasis-wonderwall/)

  • templatetag
  • email
  • antispam
Read More

SMTPConnection with Return-Path

Sometimes when sending email you want to specify a Return-Path different from the "From:" address on the email. The Return-Path is used for bounced email and is required for [VERP](http://en.wikipedia.org/wiki/VERP). This class overrides SMTPConnection so that you can specify return_path.

  • email
Read More
Author: sgb
  • 2
  • 3

Auto slug field

New field type which allows prepopulate_from to work not only from javascript but in python too. If the slugfield has unique=True creates a unique slug too.

  • slug
  • field
  • auto
  • prepopulate_from
Read More

Username genrator

This function generate an username based on the user's full name. First it tries to use the first name first letter plus the last name, second it tires the first name plus the last name first latter, and at last it tries to use the first name with a sequential number at the end. The username generated are all lowercase and ASCII only characters.

  • auth
  • username
  • name
Read More

Calendar table

Creates a filter for displaying calendars. Passed value is a dict of dicts of arrays: that is, indexed by year, then by month. The list of month days is used to generate links in the format specified by the argument. If a particular day is *not* in the list, then no link will be generated and it will just display a number for that day. **EXAMPLE** `{{ calendar|calendar_table:"/schedules/calendar/[Y]-[m]-[d]/" }}`

  • calendar
  • table
Read More

Simple View Middleware to allow a Prefilter

This allows you to define a 'prefilter' function in your view modules which will be invoked before any view in that same. This provides an easy place to decorate the request or modify arguments. For simplicity it doesn't allow configuration of the name of the prefilter function. I also skipped recursing into parent modules since that's somewhat edgecase.

  • middleware
  • process_view
  • prefilter
  • beforefilter
Read More

Test runner with coverage

A replacement test runner which outputs a coverage report after the tests. Simply change your ``TEST_RUNNER`` setting to point to ``run_tests_with_coverage`` and you're good to go. Note that 'as-is' this snippet reports the coverage of all modules underneath the app, by walking the directory tree and loading all of the .py modules (this may be a naive approach). If you change it to use `get_coverage_modules()` instead, it will only display the coverage of modules that have been imported by the test suite, using the Python `inspect` lib, which may be more reliable. Uses [coverage.py](http://nedbatchelder.com/code/modules/coverage.html). Based on ideas from: [1](http://www.thoughtspark.org/node/6), [2](http://blogs.23.nu/c0re/stories/15428/) and [3](http://siddhi.blogspot.com/2007/04/code-coverage-for-your-django-code.html)

  • test
  • runner
  • coverage
Read More