Login

Most bookmarked snippets

Snippet List

invoke pyflakes via manage.py

Invokes [pyflakes](http://divmod.org/trac/wiki/DivmodPyflakes) diagnostic tool as a `manage.py` command. Save as `flakes.py`, since `pyflakes.py` will collide with `pyflakes` module. I needed to invoke pyflakes as management command, because I alter `sys.path` in my `manage.py`, so system-wide pyflakes would not see project-local modules. Provides possibility of ignoring warnings by adding text `pyflakes:ignore` in a comment at end of offending line. Returns non-zero status to system when non-ignored warnings are found. Accepts list of directories or files as arguments. When no arguments are given, `PYFLAKES_DEFAULT_ARGS` setting is used (list of strings, by default `['.']`).

  • management
  • pyflakes
  • flakes
Read More

GzipFileSystemStorage

`GzipFileSystemStorage` is a `FileSystemStorage` subclass that transparently compresses files. [More Info](http://theidioteque.net/blog/2009/9/29/gzipfilesystemstorage/)

  • compression
  • file
  • gzip
  • storage
  • compress
Read More

Twitterfy

Improved version of my snippet #1346. Now works correctly with multiple usernames and hash tags. Both twitter usernames and hashtags are converted into links to twitter profiles and twitter search. Updated, forgot about underscores in usernames.

  • template-filter
  • twitter
  • hash-tag
  • at-reply
Read More

create and authenticate an anonymous user

If you want anonymous visitors to your site, or parts of your site to be authenticated as real users so that you can treat them as such in your views and models, use this snippet. Add the above AuthenticationBackendAnonymous middleware into AUTHENTICATION_BACKENDS in your settings.py and use the snippet anonymous_or_real(request) in your views, which returns a user. Comment out the bit where it creates a profile if you are not using profiles.

  • authentication
  • anonymous
Read More

Technical 500 by group membership

Based loosely on [Eric's middleware](http://ericholscher.com/blog/2009/sep/5/debugging-django-production-revisited/), this middleware will show the technical 500 page (which you'd get if DEBUG == True) to any user who is (1) superuser and (2) a member of the settings.TECHNICAL_500_GROUP_NAME group. (If no setting exists, 'Technical Errors' is the presumed group name. I agreed with the comments that caching should be unnecessary given the (presumptive) edge case of exception + superuser. Assuming you don't have tons of superusers, this code is a good bit simpler.

  • admin
  • user
  • auth
  • debugging
  • 500
Read More

Month / Year dropdown widget

This is an adaption of [django.forms.extras.widgets.SelectDateWidget](http://code.djangoproject.com/browser/django/trunk/django/forms/extras/widgets.py#L16) which has no day dropdown - it still produces a date but with the day set to 1. Example use class myForm(forms.Form): # ... date = forms.DateField( required=False, widget=MonthYearWidget(years=xrange(2004,2010)) )

  • date
  • year
  • credit-card
  • month
Read More

@url decorator improvements

A slight modification (and, I think, improvement) of the URL decorator found in [snippet 395](http://www.djangosnippets.org/snippets/395/). What's different between this snippet and 395? 1. We use `django.conf.urls.defaults.url()` when adding patterns 2. We support arbitrary arguments to the `url()` method (like `name="foo"`) 3. We _do not_ support multiple url patterns (this didn't seem useful to me, but if it is I can add it back.)

  • urls
  • url
  • decorator
  • decorators
  • urlpatterns
Read More

Show users' full names for foreign keys in admin

This is a ModelAdmin base class you can use to make foreign key references to User a bit nicer in admin. In addition to showing a user's username, it also shows their full name too (if they have one and it differs from the username). **2009-08-14**: updated to handle many to many fields and easily configure whether to always show the username (if it differs from full name)

  • user
  • modeladmin
  • get_full_name
Read More

format output as table

Ever wished you could have pretty SQL-like output for a python object (e.g., a list of dicts) while you're debugging your code? This function will do just that. Simply pass it an object that is an iterable of dictionaries and it returns it in an easy-to-read table, similar to the output of commandline SQL. Example: from tablelize import tableize from django.contrib.auth.models import User print(tableize(User.objects.values('email', 'first_name', 'last_name'))) +------------+-----------+-------------------+ | first_name | last_name | email | +------------+-----------+-------------------+ | Test | User | [email protected] | | Another | User | [email protected] | +------------+-----------+-------------------+

  • format
  • table
  • output
  • tablize
  • tableize
Read More

another UserForeignKey

This is another foreign key to User model. User is automatically associated before save. Requires: [ThreadlocalsMiddleware](http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser) Inspired by: [snippet 509](http://www.djangosnippets.org/snippets/509/)

  • foreignkey
  • model
  • user
  • field
  • users
  • user-foreign-key
Read More

Generic AJAX app

This is based on the Admin app functionality for dispatching calls. Once you put these two files in place then add the following to urls.py: from myProject import ajax urlpatterns = patterns('', ... # Add this to the urlpatterns list (r'^ajax/(.*)', ajax.dispatcher.urls), ...) you register a function or method with a name like so: from django.contrib import ajax def myAutoCompleteCall(request): ... ajax.dispatcher.register('myAutoComplete', myAutoCompleteCall) Then you can use the url: `http://www.mysite.com/ajax/myAutoComplete` Previously I had placed this app in the django\\contrib directory because I wanted to use it in an Admin app mod. Since the release of 1.1 I was able to move it out into a standard app because of the new `formfield_overrides` property of the `ModelAdmin` class.

  • ajax
  • django
Read More

Row-Level, URL-based permissions for FlatPages

I'm using Django's FlatPages, but I want to be able to restrict admin access to Users based on a FlatPage url. For example, User John Doe should be able to edit any FlatPage objects whose URL begins with `/johndoe/` (such as `/johndoe/about/` or `/johndoe/projects/whatever/`). For this to work, John Doe would already need the appropriate admin permissions for FlatPage (such as can_add and can_change). I have set this up as a separate *flatpage_addons* app. It consists of the **Permission** model, which maps a starting URL to one or more django Users. It consists of the minimal necessary admin code so Permissions can be created using the admin. The bulk of this code consists of the *ifhasflatpagepermission* template tag as well as the *flatpage_result_list* inclusion tag. The former works much like django's existing *if*, *else*, *endif* tags while the latter is modified from the django admin's *result_list* inclusion tag. This may not be the most elegant solution to my problem, but so far it works for me. Any comments or suggestions are welcome!

  • urls
  • url
  • permission
  • permissions
  • flatpage
  • flatpages
Read More

Sorl Thumbnail + Amazon S3

**General notes:** - Set MEDIA_URL (or whatever you use for uploaded content to point to S3 (ie. MEDIA_URL = "http://s3.amazonaws.com/MyBucket/")) - Put django-storage in project_root/libraries, or change the paths to make you happy. - This uses the functionality of django-storage, but *not* as DEFAULT_FILE_STORAGE. The functionality works like so: **Getting stuff to S3** - On file upload of a noted model, a copy of the uploaded file is saved to S3. - On any thumbnail generation, a copy is also saved to S3. **On a page load:** 1. We check to see if the thumbnail exists locally. If so, we assume it's been sent to S3 and move on. 2. If it's missing, we check to see if S3 has a copy. If so, we download it and move on. 3. If the thumb is missing, we check to see if the source image exists. If so, we make a new thumb (which uploads itself to S3), and move on. 4. If the source is also missing, we see if it's on S3, and if so, get it, thumb it, and push the thumb back up, and move on. 5. If all of that fails, somebody deleted the image, or things have gone fubar'd. **Advantages:** - Thumbs are checked locally, so everything after the initial creation is very fast. - You can clear out local files to save disk space on the server (one assumes you needed S3 for a reason), and trust that only the thumbs should ever be downloaded. - If you want to be really clever, you can delete the original source files, and zero-byte the thumbs. This means very little space cost, and everything still works. - If you're not actually low on disk space, Sorl Thumbnail keeps working just like it did, except your content is served by S3. **Problems:** - My python-fu is not as strong as those who wrote Sorl Thumbnail. I did tweak their code. Something may be wonky. YMMV. - The relative_source property is a hack, and if the first 7 characters of the filename are repeated somewhere, step 4 above will fail. - Upload is slow, and the first thumbnailing is slow, because we wait for the transfers to S3 to complete. This isn't django-storage, so things do genuinely take longer.

  • image
  • thumbnail
  • s3
  • amazon
  • sorl
Read More

3110 snippets posted so far.