Login

All snippets written in Python

2956 snippets

Snippet List

CountryField (UN Country List, 3 Char Codes)

**Adapted from** [CountryField](http://www.djangosnippets.org/snippets/494/) - **Initial thanks to marinho** Uses the UN country list listed in the source - this provides the 3 character ISO country code. Ordered by display value and not country code. Just place anywhere you like and import CountryField to use. `country = CountryField(verbose_name="Country", help_text="The registrant's country of residence.")`

  • forms
  • form
  • field
  • list
  • country
  • countries
  • custom
  • custom-field
  • countryfield
  • countrys
Read More
Author: djm
  • 1
  • 1

Null Field Admin Filter

This patch adds a new admin Filter, for Filtering nullable fields. It adds 3 possible choices: 'All' (no filter), 'Null' (it applies field__isnull=True filter), and 'With Value' (it filters null values). This patch is interesting when you have a Integer or String fields and you want to filter wether a value is set or not. In other case, it would show too many filtering options. Remember this is a patch and you must modify a django file in `django/contrib/admin/filterspecs.py`

  • filter
  • admin
  • null
Read More

Unsharp Mask with PIL and PythonMagick

**A Magick PIL** I used to do my image conversions with ImageMagick and system calls back in my PHP days. With Django PIL is the obvious choice for most image stuff, but frustrated by the lack of a proper unsharp mask function for PIL I found some code in the bits and pieces of documentation for PythonMagick. (yes I know, Kevin Cabazon wrote PIL_usm, but I could not get it to work, probably due to my inexperience. Anyway, this code makes it easy to convert back and forth from PIL to PythonMagick (maybe not such a good idea on a memory tight high loaded production server, but no problem on my private server (Pentium-M @ 1.8 Ghz with 1 GB Mem.) **usage:** usm takes a PIL image object. Radius and sigma is in pixels, amount 1 compares to 100% in photoshop, threshold 0.004 ~ (1/256) compares to 1 in photoshop: I'm using r=1,s=0.5,a=0.8,t=0.016 for roughly 800x600 images created from 3000x2000 (6MP) images. Experiment for your own preferences.

  • image
  • pil
  • sharpen
  • thumbnails
  • pythonmagick
  • usm
Read More

ModelForm ExtJS JSON Encoder

from http://www.djangosnippets.org/snippets/792/ from utils.extjs import ExtJSONEncoder from django.utils.safestring import mark_safe class TestForm(forms.ModelForm): class Meta: model = TestModel def as_ext(self): return mark_safe(simplejson.dumps(self,cls=ExtJSONEncoder))

  • json
  • modelform
  • extjs
Read More

Update Related Object Fields

Some times I want to change the `owner` of an object to another user - problem is the object often has a lot of other objects pointing to them - I also want to update those fields. This is a generic snippet for doing just that! For instance: change_owner(obj, new_owner_id): return update_related_field(obj, new_owner_id, field="user")

  • related
  • update
Read More

Facebook Connect Middleware

This middleware will look for the cookies set when a Facebook Connect user authenticates to your site, read those cookies, determine if the logged in user is your Facebook friend and then log that user into your Django-powered site. If you don't need the bit about friend verification, it should be trivial to strip out. There are a couple of other things that are needed to get FB Connect working with your site, and you can find a more detailed entry [here (http://nyquistrate.com/django/facebook-connect/)](http://nyquistrate.com/django/facebook-connect/).

  • middleware
  • facebook
  • facebook-connect
Read More

Safing HTML Text Input

Personally I hate using markdown for text input just so it can be converted into HTML. Markdown languages almost always don't support some thing I want to do; thus, why not just use HTML in the first place. Well because you don't want anybody posting any kind of HTML on your site. Solution, instead of making your users learn markdown, let them enter HTML and filter out bad tags. This is a filter I use to filter HTML for only certain allowed tags. The allowed tags can be configured with the **allowedhtml** list. To make your text input even more user friendly use a Javascript HTML editor like [FCK Editor](http://www.fckeditor.net/) so your users will have a nice GUI editor.

  • template
  • filter
  • markup
  • markdown
  • html
Read More

Full Featured Gravatar Tag

Simply returns a created gravatar url based on input. Creates the url utilizing the full gravatar url inputs as defined at http://en.gravatar.com/site/implement/url.

  • tag
  • simple_tag
  • avatar
  • gravatar
Read More

BigIntegerField and BigAutoField

Allows to create bigint (mysql), bigserial (psql), or NUMBER(19) (oracle) fields which have auto-increment set by using the AutoField of django, therefore ensuring that the ID gets updated in the instance when calling its 'save()' method. If you would only subclass IntegerField to BigIntegerField and use that as your primary key, your model instance you create would not get the id attribute set when calling 'save()', buy instead you would have to query and load the instance from the DB again to get the ID.

  • "primary
  • key"
  • bigserial
  • bigint
  • auto_increment
Read More
Author: fnl
  • 1
  • 2

A GET string modifier templatetag

This template tag takes the current GET query, and modifies or adds the value you specify. This is great for GET-query-driven views, where you want to provide URLs which reconfigure the view somehow. **Example Usage:** `{% get_string "sort_by" "date" %}` returns `all=your&current=get&variables=plus&sort_by=date`

  • templatetag
  • get
  • context
  • request
Read More

Using Django Generics with Jinja2

Jinja2, while a great replacement for Django templates, is not a drop-in replacement for it. I wanted to use Photologue with my Jinja templates, but because Photologue uses Django generics, so I decided to see if I could use Jinja2 with generics, and then only modify the templates. It was a bit of work, but I seem to have done it. Django generics can take template_loader as an option, so if you have the same interface, things should just work. The template must accept RequestContext as an argument to render(), so here we subclass jinja2.Template and when it receives Django's RequestContext object, it creates a flat dictionary from it, which jinja2 can work with.

  • django
  • jinja
  • jinja2
Read More
Author: rmt
  • 1
  • 4

Database Cache Management View

A simple view used to manage the page cache stored in the database (here Postgresql in the django_cache table, you also have to set correctly CACHE_TABLE_OID, by the OID of the cache table (you can get it in PgAdmin)

  • admin
  • cache
  • view
  • postgresql
  • management
Read More

Cookieless Session Middleware

This middleware will put the sessionid in every place that it might be needed, I mean, as a hidden input in every form, at the end of the document as a javascrit variable to allow the AJAX request use it and of course as a GET variable of the request. To make it work correctly the MIDDLEWARE_CLASSES tuple must be in this order: ` 'CookielessSessionPreMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'CookielessSessionPosMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ` Hope it work for someone else out there.

  • middleware
  • cookie
  • cookieless
  • less
Read More

Cycling MEDIA_URL context processor

This is a context processor that will allow you to cycle the values of your MEDIA_URL context variable. It will cycle through the urls defined in settings.MEDIA_URLS, so that you can distribute your media url's between multiple servers.

  • cycle
  • media_url
Read More