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.
This is an extension of the DecimalField database field that uses my [Currency Object](http://www.djangosnippets.org/snippets/1525/), [Currency Widget](http://www.djangosnippets.org/snippets/1526/), and [Currency Form Field](http://www.djangosnippets.org/snippets/1527/).
I placed my Currency object in the Django\\utils directory, the widget in Django\\froms\\widgets_special.py, and the form field in Django\\forms\\fields_special.py because I integrated this set of currency objects into the Admin app ( [here](http://www.djangosnippets.org/snippets/1529/) ) and it was just easier to have everything within Django.
UPDATE 08-18-2009: Added 'import decimal' and modified to_python slightly.
The rest of the series: [Currency Object](http://www.djangosnippets.org/snippets/1525/), [Currency Widget](http://www.djangosnippets.org/snippets/1526/), [Currency Form Field](http://www.djangosnippets.org/snippets/1527/), [Admin Integration](http://www.djangosnippets.org/snippets/1529/)
This is an extension of the DecimalField form field that uses my [Currency Object](http://www.djangosnippets.org/snippets/1525/) and [Currency Widget](http://www.djangosnippets.org/snippets/1526/).
I placed my Currency object in the Django\\utils directory and the widget in Django\\froms\\widgets_special.py because I integrated a set of currency objects into the Admin app ( [here](http://www.djangosnippets.org/snippets/1529/) ) and it was just easier to have everything within Django.
UPDATE 07-30-2009: Add the parse_string argument to properly test the string format as per the update to the [Currency Object](http://www.djangosnippets.org/snippets/1525/)
UPDATE 09-15-2009: Properly handle None's in the clean method
The rest of the series: [Currency Object](http://www.djangosnippets.org/snippets/1525/), [Currency Widget](http://www.djangosnippets.org/snippets/1526/), [Currency DB Field](http://www.djangosnippets.org/snippets/1528/), [Admin Integration](http://www.djangosnippets.org/snippets/1529/)
This is a simple TextInput widget that uses my [Currency object](http://www.djangosnippets.org/snippets/1525/).
I placed my Currency object in the Django utils directory because I integrated a set of currency objects into the Admin app ( [here](http://www.djangosnippets.org/snippets/1529/) ) and it was just easier to have everything within Django.
The rest of the series: [Currency Object](http://www.djangosnippets.org/snippets/1525/), [Currency Form Field](http://www.djangosnippets.org/snippets/1527/), [Currency DB Field](http://www.djangosnippets.org/snippets/1528/), [Admin Integration](http://www.djangosnippets.org/snippets/1529/)
Limit rate request decorator for view.
Authenificated user can't request decorated view often then timeout.
Usage:
@limit_request_rate(time_beetween_request_sec)
def my_view(request):
...
get_cell_value from [here](http://code.activestate.com/recipes/439096/)
This template tag was built to be used in web applications that are permission based. It renders the html for an html link tag if the user has permissions to access the view (if not, returns an empty string). It also checks if the current token is the active url address and, if so, adds class="active" to the html link for presentation purposes.
Example usage:
1. {% url home as home_url %}
{% get_link_if_allowed home_url "Home" %}
2. {% url project_dashboard project.id as project_dashboard_url %}
{% get_link_if_allowed project_dashboard_url "Projects" %}
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".
This is a simple way to embed images in emails, rather than use absolute links, which many clients will not show by default. It has not undergone extensive testing but it should get you started. Comments / suggestions welcome.
This snippet parses the output file of inspectdb and does some alterations. Mostly useful for people who regenerates models from constantly changing legacy databases.
The snippet will:
*Add quotes around foreign key classes, so the ordering is not significant
*Append a related_name property to each foreign key with the value
model class name + db_column name to evade collisions in reverse queries like:
example.model: Reverse query name for field 'foreignkey' clashes with related field 'model2.foreignkey'. Add a related_name argument to the definition for 'foreignkey'.
There's a slight performance degradation with using quotes class name instead of passing the class though.
Just a quick tip on how to use the pyfacebook django middleware as a decorator since you probably dont want to add the facebook object to all incoming requests.
This code monkey-patches the default User model to rather use a primary key of UUIDField (see http://www.djangosnippets.org/snippets/1496/). This code also makes the email field required. This code is wildly dangerous, not completely future proof, and probably not advisable to use. If you do wish to use it, it will be easiest to implement on a fresh db with a syncdb. If you need to migrate existing user data the onus is on you to figure out an appropriate db migration plan.
I placed this code in a models.py, but it is probably more reliably placed in urls.py
This cache_page decorator can be used in replacement to Django's django.views.decorators.cache.cache_page.
It resolves two problems:
- invalidation (its cache key is not dependent of header nor request, then you can use model signals (or method 'put' in Google App Engine) to invalidate a URL or a list of them)
- easier to scale (can be used at once memcached server by many differente servers)
Feel free to show me where it can have problems or limitations.
**Updated and improved a lot**
A simple tag to render breadcrumbs.
Usage:
{% load breadcrumbs %}
{% breadcrumbs "['Home','Home','home']" "['Articles','Articles','articles']" "['object','object','object.get_absolute_url']" %}
Loads up the template in "modules/breadcrumbs.html" and renders it with a list of items.
You can provide the tag either with plain text stuff and named urls as the third argument ( any more arguments per bracket-block is parsed as args / kwargs for the reverse() call ) or the object directly, and the script tries after failing the reverse() to resolve the provided arguments.
Have pun.
You're looking at the most-bookmarked snippets on the site; if you'd like to help useful snippets show up here, sign up for an account and you'll get your own bookmarks list.