Login

Top-rated snippets

Snippet List

Slugify alternative

I prefer to use this slugification function rather than the one included with Django. It uses underscores instead of dashes for spaces, and allows dashes and periods to occur normally in the string. I decided on this when considering reasonable slugified titles such as... object-relational_mapper_2.5 ten_reasons_web-2.0_rocks django-trunk_0.99_updated

  • filter
  • slugs
  • slug
  • slugify
Read More

Authenticate with Email Address

This code gives you the ability to authenticate a user by their email address instead of the username. I've also added the ability to authenticate via LDAP. Some code used from this [snippet](http://www.djangosnippets.org/snippets/74/)

  • admin
  • user
  • email
  • authenticate
  • ldap
Read More

BritishDateField

The date field in the newforms module includes American style mm/dd/yyyy , which anyone outside the US will recognise as being complete madness. This date field behaves sensibly.

  • newforms
Read More

simple text image view

**Credit goes to** [Andrew Gwozdziewycz](http://www.23excuses.com/2006/Jun/30/simple-django-view-for-dynamic-text-replacement/) and [Jacob Kaplan-Moss](http://www.jacobian.org/writing/2006/jun/30/improved-text-image-view/) This is basically their code. Only differences: * orientation can be customized * size can be customized * GIF-Image with transparency is created Note: Because of the minimum palette that's used, the font isn't antialiased/smoothened. My url for this view looks like so: (r'^img/(?P<fontalias>\w+)/(?P<orientation>(normal|left|right))/$', 'view.text_to_image')

  • text
  • image
  • text-image-view
Read More

Install Django on TextDrive

This script automates the process of installing Lighttpd, Flup, Django and a Django app (with init script) on a TextDrive shared server. Usage instructions: http://textusers.com/wiki/Installing_Django # Changelog * April 5, 2007 * Added (www.\)? conditional in Lighty conf * Updated to Django 0.96

  • install-django
  • textdrive
Read More

Convert LaTeX templates to various output formats

**The code is a bit messy and may include bugs ;-) Anyway, I want to clean it up and add features (see below).** The `process_latex()` function will read the given template, render it with a custom context and convert it into the desired output format by running it through pdflatex. Depending on the `outfile` parameter, the output will either be returned (for a response object) or written to the path specified in `outfile` (useful for `save()` in models which generate static, unique files). **TODO** * Error handling in case pdflatex breaks (non-zero return value) * Optionally returning a HttpResponse with the correct mimetype and Content-Disposition set to attachement and an appropriate filename * RequestContext instead of Context (passing the Context object instead of a dict) **CREDITS** Credits also go to ronny for the names dict :-P

  • template
  • django
  • pdf
  • dvi
  • png
  • latex
  • pdflatex
Read More

send_file and send_data

Simple functions for downloading files - send_data sends the data directly, send_file as attachment. May need optimizing for large files.

  • files
  • download
Read More

AppendSlashMiddleware

**I won't be able to debug this until tonight... so if you see this message there may still be bugs in this** This Middleware replaces the behavior of the APPEND_SLASH in the CommonMiddleware. Please set APPEND_SLASH = False if you are going to use this Middleware. Add the key defined by APPENDSLASH to the view_kwargs and a True or False to determine the behaivor of the appended slashes. For instance I set my DEFAULTBEHAVIOR to the default of True, then to override that behaivor I add 'AppendSlash':False to the URLs that I wish to have no slash. **Example** ` urlpatterns = patterns('some_site.some_app.views', (r'^test/no_append$','test_no_append',{'AppendSlash':False}), (r'^test/append/$','test_append'), ) `

  • middleware
Read More

Render dynamically assigned fields in a template

**Problem:** You want to render an arbitrary number of fields assigned dynamically, as in [snippet #27](http://www.djangosnippets.org/snippets/27/), but using multiple `if` statements in a template would be tedious. **Solution:** newforms BoundField The example demonstrates a form with medication fields. We don't know in advance how many meds will be prescribed to a patient, but we want to display a minimum of 4 medication fields, each consisting of a label, name, and dosage. My code uses a cheap hack of assigning a .bf attribute to the fields during __init__, but it's easy to render in a template loop: `{% for med in form.med_list %}` *Special thanks to Honza for advice on BoundField.*

  • template
  • dynamic
  • boundfield
  • render
Read More

Url filter middleware

How to config it ------------------ You can treat it as a micro url filter framework. Before you using it, you should setup some options about it. The option entry shoud be like this: FILTERS = ( (r'^user/(?P<user_id>\d+)/', 'apps.users.filter.check_valid_user'), ) FILTERS should be a list or tuple with two elements tuple item. The format should be like: (url_patterns, function) And url_patterns could be a single regex expression or a list/tuple regex expressions, So you can set multi regex expression in it. And the regulation is just like url dispatch, as above example, the url pattern is: r'^user/(?P<user_id>\d+)/' So you can see, you can set parameter name `user_id`, then it'll be passed to the function behind. Function can be a string format, just like above example, and it can be also a real function object. It'll only impact request. How to write filter function ------------------------------- According above example, I define a url pattern, and what to check if the user is a valid user, and if the user is visiting his own urls, so the filter function could be: from django.contrib.auth.models import User from utils.common import render_template def check_valid_user(request, user_id): if request.user.is_anonymous(): return render_template(request, 'users/user_login.html', {'next':'%s' % request.path}) try: person = User.objects.get(pk=int(user_id)) except User.DoesNotExist: return render_template(request, 'error.html', {'message':_("User ID (%s) is not existed!") % user_id}) if person.id != request.user.id: return render_template(request, 'error.html', {'message':_('You have no right to view the page!')}) I think the code is very clear. And you can use it filtermiddleware to do like user authentication check, and other checking for url. BTW, render_template is comes from [Snippets #4](http://www.djangosnippets.org/snippets/4/)

  • middleware
  • filter
  • url
Read More

getattr template filter

Put inside `mysite/templatetags/getattr.py` Add `mysite` to your `INSTALLED_APPS` In your template: {% load getattr %} {{ myobject|getattr:"theattr,default value" }} Thanks to pterk for optimizations! \\o/

  • template
  • filter
  • get
Read More

3110 snippets posted so far.