Login

All snippets written in Python

Snippet List

django redirects middleware a bit more fleixble

This is replace for django.contrib.redirects.RedirectFallbackMiddleware which redirects exact matches as well as startswith matches for the redirect.old_path I had a problem with my urls, because are dynamically generic, so I can't create one redirect entry on the database for each possible url. So I made django redirects to search any redirect with the exact match or any database entry being the head of my url, for example: I have django redirects which redirects /calendars/3434/ --> / . But when I have a 404 on /calendars/3434/c/2009/10/23/ now it redirects properly. So my redirects now acts as /calendars/3434/*

  • generic
  • redirects
  • contrib
Read More

Custom model field for mysql time type.

Django does not have a suitable model field can process time type in mysql, the DateTimeField built-in django can not process more than 24 hours. That's why the code born. **Simply usage** `from myapp.models import TimeAsTimeDeltaField, SECONDS_PER_MIN, SECONDS_PER_HOUR, SECONDS_PER_DAY class EstimatedTime: days = None hours = None minutes = None seconds = None class Case(models.Model): estimated_time = TimeAsTimeDeltaField(null=True, blank=True) def get_estimated_time(self): estimated_time = EstimatedTime() if self.estimated_time: total_seconds = self.estimated_time.seconds + (self.estimated_time.days * SECONDS_PER_DAY) days = total_seconds / SECONDS_PER_DAY hours = total_seconds / SECONDS_PER_HOUR - days * 24 minutes = total_seconds / SECONDS_PER_MIN - hours * 60 - days * 24 * 60 seconds = total_seconds % SECONDS_PER_MIN estimated_time.days = days estimated_time.hours = hours estimated_time.minutes = minutes estimated_time.seconds = seconds return estimated_time else: return estimated_time

  • models
  • orm
  • database
  • field
  • timedelta
Read More

middleware for user_passes_test

Middleware to decorate views with user_passes_test in a centralized, url-matching manner. Makes it easy to apply permissions across large sections or all of a site.

  • auth
  • permissions
  • decorators
Read More

A Lazy ChoiceField implementation

Sometimes it is useful to have a ChoiceField which calculates its choices at runtime, when a new instance of a form containing it, is generated. And this is what `LazyChoiceField` does. The `choices` argument must be an *iterable* as for `ChoiceField`. **Usage example** from django import forms DynamicApplicationList = [] class MyForm(forms.Form): dynamic_choice = LazyChoiceField(choices = DynamicApplicationList) `DynamicApplicationList` can now be updated dynamically.

  • fields
  • choice
  • forms
  • form
  • field
Read More

very archive view

I tried to think of a way to use generic views to show all my blog posts on one page organized chronologically with each post title under one month name and all the month names under one year name. Like so: ` 2009 October My last example blog entry Entry even before the last one First of October September Only one entry in Sept. 2008 December It is cold in December First posting of my blog ` I could not think of a way to do this using generic views, before I wrote a view and some template logic that does. The template logic is here: [http://www.djangosnippets.org/snippets/1765/](http://www.djangosnippets.org/snippets/1765/) Any suggestions for design patterns are greatly appreciated.

  • archive
  • blog-entry
Read More

Nice form errors

Nicely output all form errors in one block, using field labels rather than the field attribute names.

  • forms
  • template-filter
  • errors
Read More

Continuous Integration command

This command, `runtester` will run the test suite whenever files are modified. It takes the apps to test as arguments; if no apps are given the entire test suite is run. Use this command just as `runserver` is used; fire it up in a shell and it does its thing. Copy this snippet into `django/core/management/commands/runtester.py`.

  • testing
  • tests
  • commands
  • command
  • test-runner
Read More

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

Rails-like environments using Django

This is a replacement for settings.py, which moves the actual settings files into a directory called "env" and establishes different versions for different settings of the environment variable DJANGO_ENV. At runtime, the specified development environment can be found and loaded into the local context of settings.py, which is then picked up by whatever routine manage.py is kicking off.

  • django
  • rails
  • environment
Read More

yet another digg style paginator

put this code into your application's `__init__.py` it adds a mixin to the `Paginator` class that implements a digg style pagination. the mixin has just one method called `digg_page_range` that takes the current page object as the parameter. this method is an iterator which yields page numbers with `None` values representing gaps. this iterator is similar to the original paginator's method `page_range` and it can be used in your code to emit the needed markup.

  • paginator
  • digg
Read More

admin filters as select boxes

This templatetag let's you output a form with select boxes instead of the ul's for filters. Uses some hacks to get the param names out of query strings. This would be a lot easier if filterspecs defined params instead of query strings (if filter tag would handle the encoding)

  • filter
  • admin
  • filterspec
Read More
Author: gzy
  • -1
  • 3

parse date template tag

Return a datetime corresponding to date_string, parsed according to format. I had the need for such a thing while working with an API that returned JSON that I fed, via simplejson, directly to a template, and didn't want to change the data structure just for this one piece.

  • datetime
  • parse
  • strptime
Read More

URL models

You can use `UrlModel` to provide URL functionality to any instance of any model and any language (language support can be removed from this). Each model must have own view method, that returns HttpResponse. I was inspired by Flatpages. It is useful for small sites and static pages. `class Page(UrlModel): text = models.TextField() def view(self, request) # do something here return HttpResponse(...)`

  • middleware
  • urls
  • models
  • foreignkey
  • model
  • generic
  • url
  • foreign-key
  • genericforeignkey
  • contenttypes
  • 404
  • contenttype
  • content-type
Read More

Load static media from secure (SSL) static server (Context Processor)

If you request static files such as images, javascript or css using http rather than https, the browser will complain that your site is not secure. This simple context processor will replace http:// with https:// in your MEDIA_URL if your static files are being included from an https page. In your settings.py just replace 'django.core.context_processors.media' with your new context processor.

  • files
  • ssl
  • context
  • static
  • processor
  • secure
  • content
  • media_url
Read More

2956 snippets posted so far.