Login

Top-rated snippets

Snippet List

automating twitter

Assume you have a model called Delegate and you want to tweet whenever a new Delegate registers, the code above will do this. You need to install python-twitter.

  • twitter
Read More

Profiling Middleware w/sorting

Based *very heavily* on the middleware in [this snippet](http://www.djangosnippets.org/snippets/727/). As with that one, append '?prof' to the URL to see profiling output instead of page output. The big change is that you can also pass an argument to control sorting. For example, you can append '?prof=cumulative' to sort the results by the cumulative time consumed. See the [documentation on the Stats class](http://docs.python.org/library/profile.html#pstats.Stats.sort_stats) for all the options.

  • middleware
  • performance
  • profiler
Read More

Test Server Thread

This class runs a django test server in another thread. This is very useful for e.g. selenium integration. Simple to integrate into django test framework. Usage: server = TestServerThread("127.0.0.1", "8081") server.start() # Run tests e.g. req = urllib.urlopen("http://127.0.0.1:8081") contents = req.read() server.stop() ps. I don't actually double space my code :). Not sure whats up with that!

  • thread
  • test
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

DRY Fieldsets

I've devised a DRY method of declaring django fieldsets: ** Example usage: ** 1. Include the attached code in `fieldsets.py` 2. `models.py`: from django.db import models from fieldsets import Fieldset, ModelWithFieldsets class Person(ModelWithFieldsets): #instead of models.Model # this field will be placed in nameless fieldset example_field = models.IntegerField() # this fieldset will be grouped into one row Fieldset(grouped=True) first_name = models.CharField(max_length=64) surname = models.CharField(max_length=64) Fieldset("Contact Details", classes=('collapse',)) mobile_phone = models.CharField(max_length=10) email_address = models.EmailField() Fieldset("Address") street_address = models.CharField(max_length=255) # the next two fields will be grouped into one row of this fieldset Fieldset.new_group(2) suburb = models.CharField(max_length=64) state = models.CharField(max_length=64) 3. `admin.py`: from django.contrib import admin from models import Person from fieldsets import Fieldset class PersonAdmin(admin.ModelAdmin): fieldsets = Fieldset.get_fieldsets(Person) admin.site.register(Person, PersonAdmin) This example produces the equivalent of manually typing: fieldsets = ( (None, {'fields': ('example_field')}), (None, {'fields': (('first_name', 'surname'),)}), ('Contact Details', { 'fields': ('mobile_phone', 'email_address'), 'classes': ('collapse',)}), ('Address', {'fields': ('street_address', ('suburb', 'state'))}) ) But now if you want to rearrange your fields, rename, delete, insert, etc, you won't need to remember to update the fieldsets in the ModelAdmin. This implementation is a bit of a hack, but I believe a cleaner equivalent should be implemented in django itself.

  • admin
  • dry
  • fieldsets
Read More

manage.py for eclipse with pydev debugging

This code is referenced in a [screencast](http://blog.vlku.com/index.php/2009/06/10/djangoeclipse-with-code-complete-screencast/) focused on showing a user how to configure Eclipse with PyDev to give you code complete, and breakpoints inside the IDE. It comes from a [2007 blog post](http://bear330.wordpress.com/2007/10/30/how-to-debug-django- web-application-with-autoreload/) (I've replicated it in case that post ever disappears.)

  • debugging
  • pydev
  • eclipse
Read More

Django app WSGI

If you want to have your wsgi as general as possible (for eg. different environments) without any hardcoded paths, this example might help you...

  • wsgi
Read More

Sometimes Tag

Adds a templatetag that works like an if block, but . The one and only argument is a float that reflects the percentage chance. It defaults to .2, %20. {% sometimes %} <img src='spy_behind_sniper.jpg'/> {% else %} <img src='sniper.jpg'/> {% endsometimes %} -- or -- {% sometimes .001 %} You win! {% else %} Sorry, not a winner. Play again! {% endsometimes %} -- or -- {% sometimes .5 %} This shows up half the time. {% endsometimes %}

  • tag
  • random
Read More

MySQL django password function

This functions encodes a password in the same format as django. You can set the auth_user.password column with the result of this function: update `auth_user`.`password` set `password` = django_password('secret') where id = 1234;

  • function
  • password
  • mysq
  • sha
Read More

PowerDNS models

With these models, you can use your Django's database directly as backend for PowerDNS server (tested with MySQL). License: GNU GPL. More info: http://downloads.powerdns.com/documentation/html/configuring-db-connection.html#CONFIGURING-MYSQL

  • models
  • model
  • powerdns
  • dns
Read More

Digg-like pagination

My take on digg-like pagination. Save the code as 'templatetags/pagination_nav.py' in one of your apps. It relies on a 'pagination_nav.html' template. Here is a base template: {% if pages %} <div class="bottom-pagination-nav"> {% if previous_url %}<a href="{{ previous_url }}">{% else %}<span>{% endif %}&laquo; Previous{% if previous_url %}</a>{% else %}</span>{% endif %} {% for group in pages %} {% for page in group %} {% if page.current %}<span>{{ page.number }}</span>{% else %}<a href="{{ page.url }}">{{ page.number }}</a>{% endif %} {% endfor %} {% if not forloop.last %}<span>...</span>{% endif %} {% endfor %} {% if next_url %}<a href="{{ next_url }}">{% else %}<span>{% endif %}Next &raquo;{% if next_url %}</a>{% else %}</span>{% endif %} </div> {% endif %}

  • pagination
  • template-tag
  • paginator
  • digg
Read More

range tag

Create a list containing an arithmetic progression that can be iterated through in templates. Emulate the [range](http://docs.python.org/library/functions.html#range) syntax. You can use either numbers or variables. Syntax: {% num_range [start] stop [step] as some_range %} {% for i in some_range %} ... do something {% endfor %} **About the author**: Take a look at [my website](http://www.marcofucci.com)

  • template
  • tag
  • django
Read More

Word-boundary-aware string truncation template filter

This is a custom template filter that allows you to truncate a string to a maximum of num characters, but respecting word boundaries. So, for example, if `string = "This is a test string."`, then `{{ string|truncatechars:12 }}` would give you "This is a..." instead of "This is a te".

  • template
  • filter
  • truncate
  • words
Read More

VAT field

VAT field with a field to select the country and a free field for the code

  • django
  • fields
  • forms
  • form
  • field
  • formfield
  • vat
  • tva
Read More

3110 snippets posted so far.