Login

All snippets

Snippet List

monkey-patch django to use jinja2 templates for 404/500 pages and 3rd-party apps

This is heavily inspired by [http://code.google.com/p/smorgasbord/](http://code.google.com/p/smorgasbord/). But that couldn't reuse an existing jinja2 Environment, nor set filters on the Environment it created. This code assumes that you have `env` declared previously in the file as your Jinja2 Environment instance. In `settings.py`, you should set KEEP_DJANGO_TEMPLATES = ( '/django/contrib/', ) so that your Django admin still works. You can also set any other places that you do want to use Django templates there.

  • templates
  • jinja2
Read More

Case Insensitive Authentication Backend

By enabling this backend: AUTHENTICATION_BACKENDS = ( 'path.to.my.backends.CaseInsensitiveModelBackend', ) Your users will now be able to log in with their username, no matter whether the letters are upper- or lower-case.

  • auth
  • case
  • case-insensitive
  • backend
  • insensitive
Read More

copyright_since

**Example usage**: {% copyright_since 2008 %}, {% copyright_since 2009 %} **Output**: © 2008—2009, © 2009 Use this templatetag in your footer to achieve proper formatting of copyright notice.

  • datetime
  • date
  • template-tag
  • formatting
  • copyright
  • copyright-formatting
  • copyright-year
Read More

Pagination/Filtering Alphabetically

This allows you to create an alphabetical filter for a list of objects; e.g. `Browse by title: A-G H-N O-Z`. See [this entry](http://developer.yahoo.com/ypatterns/pattern.php?pattern=alphafilterlinks) in Yahoo's design pattern library for more info. NamePaginator works like Django's Paginator. You pass in a list of objects and how many you want per letter range ("page"). Then, it will dynamically generate the "pages" so that there are approximately `per_page` objects per page. By dynamically generating the letter ranges, you avoid having too many objects in some letter ranges and too few in some. If your list is heavy on one end of the letter range, there will be more pages for that range. It splits the pages on letter boundaries, so not all the pages will have exactly `per_page` objects. However, it will decide to overflow or underflow depending on which is closer to `per_page`. **NamePaginator Arguments**: `object_list`: A list, dictionary, QuerySet, or something similar. `on`: If you specified a QuerySet, this is the field it will paginate on. In the example below, we're paginating a list of Contact objects, but the `Contact.email` string is what will be used in filtering. `per_page`: How many items you want per page. **Examples:** >>> paginator = NamePaginator(Contacts.objects.all(), \ ... on="email", per_page=10) >>> paginator.num_pages 4 >>> paginator.pages [A, B-R, S-T, U-Z] >>> paginator.count 36 >>> page = paginator.page(2) >>> page 'B-R' >>> page.start_letter 'B' >>> page.end_letter 'R' >>> page.number 2 >>> page.count 8 In your view, you have something like: contact_list = Contacts.objects.all() paginator = NamePaginator(contact_list, \ on="first_name", per_page=25) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: page = paginator.page(page) except (InvalidPage): page = paginator.page(paginator.num_pages) return render_to_response('list.html', {"page": page}) In your template, have something like: {% for object in page.object_list %} ... {% endfor %} <div class="pagination"> Browse by title: {% for p in page.paginator.pages %} {% if p == page %} <span class="selected">{{ page }}</span> {% else %} <a href="?page={{ page.number }}"> {{ page }} </a> {% endif %} {% endfor %} </div> It currently only supports paginating on alphabets (not alphanumeric) and will throw an exception if any of the strings it is paginating on are blank. You can fix either of those shortcomings pretty easily, though.

  • pagination
  • paginator
  • filtering
Read More

Include entire networks in INTERNAL_IPS setting

A simple addition to the settings.py file of your project to allow you to easily specify entire network ranges as internal. This is especially useful in conjunction with other tools such as the [Django Debug Toolbar](http://github.com/robhudson/django-debug-toolbar/tree/master). After you set this up, the following test should pass test_str = """ >>> '192.168.1.5' in INTERNAL_IPS True >>> '192.168.3.5' in INTERNAL_IPS FALSE """ Requirements ------------ * The [IPy module](http://software.inl.fr/trac/wiki/IPy) Acknowledgements ---------------- Jeremy Dunck: The initial code for this idea is by Jeremy and in [Django ticket #3237](http://code.djangoproject.com/ticket/3237). I just changed the module and altered the use of the list superclass slightly. I mainly wanted to put the code here for safe keeping. Thanks Jeremy!

  • settings
  • ip-addresses
  • cidr
  • internal-ips
Read More

Custom admin widgets by field type

There are probably ways to improve the implementation, but this was something I came up with when I wanted to change the default size of all of my CharField admin fields. Now all I have to do in my ModelAdmin class is: form = get_admin_form(model) or subclass BaseAdminForm if I need extra validation or more widget customization for an individual admin form.

  • newforms
  • admin
  • widget
  • customize
Read More

Testing Email Registration

http://steven.bitsetters.com/articles/2009/03/09/testing-email-registration-flows-in-django/ Testing email registration flows is typically a pain. Most of the time I just want to sign up with a test user, get the email link and finish the flow. I also want to be able to automate the whole process without having to write some SMTP code to check some mail box for the email. The best way I’ve found to do this is just to write out your emails to some file instead of actually sending them via SMTP when your testing. Below is some code to do just that. I’ve also created a Django management script that will open the last email sent out from your application, find the first link in it and open it in your web browser. Quite handy for following email registration links without logging into your email and clicking on them manually.

  • email
  • debug
  • testing
Read More

Variable resolving URL template tag

** DEPRECATED**, use [django-reversetag @ github](http://github.com/ulope/django-reversetag/tree/master) instead. If you want to be able to use context variables as argument for the "url" template tag this is for you. Just put this code somwhere where it will be run early (like your app's _ _init_ _.py) and of you go. Usage: {% url name_of_view_or_variable arg1 arg2 %} **NOTE:** This may possibly break your site! Every view name that is passed to url will be tried to be resolved as a context variable first! So if there is a variable coincidentally named like one of your views THEN IT WILL BREAK. So far it works great for me, but keep an eye out for name clashes.

  • template
  • tag
  • url
  • context
  • variable
  • resolve
  • resolving
Read More

Template range filter

Easy to use range filter. Just in case you have to use a "clean" for loop in the template. Inspired by [Template range tag](http://www.djangosnippets.org/snippets/779/) Copy the file to your templatetags and load them. [Django doc | Custom template tags and filters](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/)

  • template
  • filter
  • range
Read More

RFC: Shim to allow view classes rather than functions

This snippet is working code, however it is not intended for proper use, rather to garner comment on an alternative style of view - using a class for views, rather than a function. While working with views, I've often felt that the traditional django code layout splits concerns in an unnatural fashion. The parameters for a view must be maintained in both the urls file as well as the view for example, and there is no neat way of grouping multiple accessor for a REST resource. This 'shim' code aims to propose an alternative architecture, that is interchangeable with the existing system. Rather than include a tuple of urls, instead a list of classes is provided. Each class models a resource, or page. Page objects have a url property and name property, so it is therefor trivial to reconstruct the url tuple from the class, but allow more simplicity and structure in relating the methods of the resource. You may notice that this structure closely follows the architecture of the web.py framework - this syntax did indeed play a part in the concept for such a structure. While this paradigm may not be suitable in all situations, I believe it promotes a simpler, more encapsulated views architecture. Any comments and feedback are welcomed. Example usage (untested, sorry): class Homepage(Page): def get(request): return HttpResponse("Hello World") urlpatterns = patterns('', Homepage, url('^existing$', existing.view.function, name = "foo"), )

  • views
  • rfc
Read More

3109 snippets posted so far.