Snippet List
The problem with supplying a Django model field with choices parameter is the way you check a value of that field in an object. You do nasty things like this:
if model_instance.choice_field == 1:
The problem of getting rid of hard-coded numbers is recognized over the internet, but I haven't found any short and understandable solution. Basically, we need a enumeration in python, that is ok to use as the Django `choices` model field argument.
I've seen a couple of solutions of DjangoSnippets. Mine is shorter and easier because it only works for integer field choices.
- choices
- integer
- enumeration
See code
- ip
- integer
- address
- modelfield
- int
This accepts values such as $1,000,000 and stores them to the database as integers. It also re-renders them to the screen using the django.contrib.humanize.intcomma method which takes 1000000 and turns it into 1,000,000. Useful for large currency fields where the decimals aren't really necessary.
- newforms
- currency
- field
- integer
- input
This function can be util for transform pattern lists like these to strings:
>>> list_to_pattern([42, 43, 44, 45])
'42-45'
>>> list_to_pattern([15, 49, 50, 51, 52])
'15,49-52'
>>> list_to_pattern([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
'0-13'
You can use also the pattern to list function at [http://www.djangosnippets.org/snippets/495/](http://www.djangosnippets.org/snippets/495/)
This function can be util for transform pattern strings like these to list:
>>> pattern_to_list('42-45')
[42, 43, 44, 45]
>>> pattern_to_list('15,49-52')
[15, 49, 50, 51, 52]
>>> pattern_to_list('0-13')
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
You can use also the list to pattern function at [http://www.djangosnippets.org/snippets/496/](http://www.djangosnippets.org/snippets/496/)
7 snippets posted so far.