Login

Tag "field"

Snippet List

Exclusive boolean field

**NOTE: I now have a better implementation of this (nicer api, less signal wrangling) available [on PyPI here](https://pypi.python.org/pypi/django-exclusivebooleanfield)** Sometimes you want to be able to make one (and only one) row in your model 'featured' or 'the default one' If you have some kind of parent model you could have a ForeignKey on the parent to hold that info, but that won't always be the case - eg you may have no parent, or multiple parent models. With the exclusive_boolean_fields() helper you can do it with or without a parent model and it possibly makes the admin interface a bit simpler.

  • field
Read More

Remove named field from fieldsets

This snipped removes a specific fields from the fieldsets. This is very useful to leave a field 'out' in the admin, likewise: def get_fieldsets(self, request, obj=None): fieldsets = super(BlaModelAdmin, self).get_fieldsets(request, obj) if not request.user.has_perm('change_blah'): remove_from_fieldsets(fieldsets, ('blah',))

  • admin
  • fieldset
  • form
  • field
  • fieldsets
Read More

Limit the output of a field

This is a really simple snippet , but is not documented well ... Whit this , you can limit the output of one field in 25 characters before you test that is equal or over 30 characters! Note that the snippet cut the text and add three points at the end (...) Enjoy!

  • form
  • field
  • output
  • limit
Read More

Stacked/Grouped Forms 2 - easy rendering forms

This snippet was inspired by [1783](http://www.djangosnippets.org/snippets/1783/). It allows simply create groups of fields for template rendering.

  • template
  • fields
  • forms
  • templates
  • fieldset
  • form
  • object
  • field
  • fieldsets
  • groups
  • stacked
  • descriptor
Read More

Custom model field for mysql time type.

Django does not have a suitable model field can process time type in mysql, the DateTimeField built-in django can not process more than 24 hours. That's why the code born. **Simply usage** `from myapp.models import TimeAsTimeDeltaField, SECONDS_PER_MIN, SECONDS_PER_HOUR, SECONDS_PER_DAY class EstimatedTime: days = None hours = None minutes = None seconds = None class Case(models.Model): estimated_time = TimeAsTimeDeltaField(null=True, blank=True) def get_estimated_time(self): estimated_time = EstimatedTime() if self.estimated_time: total_seconds = self.estimated_time.seconds + (self.estimated_time.days * SECONDS_PER_DAY) days = total_seconds / SECONDS_PER_DAY hours = total_seconds / SECONDS_PER_HOUR - days * 24 minutes = total_seconds / SECONDS_PER_MIN - hours * 60 - days * 24 * 60 seconds = total_seconds % SECONDS_PER_MIN estimated_time.days = days estimated_time.hours = hours estimated_time.minutes = minutes estimated_time.seconds = seconds return estimated_time else: return estimated_time

  • models
  • orm
  • database
  • field
  • timedelta
Read More

A Lazy ChoiceField implementation

Sometimes it is useful to have a ChoiceField which calculates its choices at runtime, when a new instance of a form containing it, is generated. And this is what `LazyChoiceField` does. The `choices` argument must be an *iterable* as for `ChoiceField`. **Usage example** from django import forms DynamicApplicationList = [] class MyForm(forms.Form): dynamic_choice = LazyChoiceField(choices = DynamicApplicationList) `DynamicApplicationList` can now be updated dynamically.

  • fields
  • choice
  • forms
  • form
  • field
Read More

Integer based MoneyField

It is supposed the aggregation on integer is fast than numeric type in database duo to how they are stored as numeric is represented as string. As money only have 2 decimal place, it can be converted to an Integer despite of its decimal point. The python class decimal.Decimal also has a shortcoming that it is not json serializable(neither cjson nor simplejson). This money field appears as a float number to the front end, so it does not meet the headache as DecimalField. The usage is very simple. In Model: class SomeModel(models.Model): ... income = MoneyField('income') ... Then treat the attribute of the model instance as a normal float type. **Notes** If you try to use aggregation on this field, you have to convert it to float by yourself. Currently I could not find any method to fix this.

  • money
  • db
  • field
Read More
Author: Jay
  • 0
  • 1

CharField powered Tags with ChoiceField widget.

Shell example: >>> pprint.pprint(settings.FORUM_TAGS) ((u'x11', 'Xorg'), (u'pacman', 'Pacman'), (u'aur', 'AUR'), (u'abs', 'ABS'), (u'howto', 'HOWTO'), (u'instalacja', 'Instalacja'), (u'offtopic', 'Offtopic')) >>> t = Thread.objects.all()[0] >>> pprint.pprint(t.tags) [{'slug': u'pacman', 'title': 'Pacman'}, {'slug': u'abs', 'title': 'ABS'}, {'slug': u'howto', 'title': 'HOWTO'}, {'slug': u'instalacja', 'title': 'Instalacja'}, {'slug': u'offtopic', 'title': 'Offtopic'}] >>> t.tags = [{'slug': 'abs'}, {'slug': 'howto'} >>> t.save() >>> t = Thread.objects.get(pk=t.pk) >>> pprint.pprint(t.tags) [{'slug': u'abs', 'title': 'ABS'}, {'slug': u'howto', 'title': 'HOWTO'}] >>> t.tags = ['Offtopic', 'HOWTO'] >>> t.save() >>> t = Thread.objects.get(pk=t.pk) >>> pprint.pprint(t.tags) [{'slug': u'howto', 'title': 'HOWTO'}, {'slug': u'offtopic', 'title': 'Offtopic'}]

  • tag
  • forms
  • field
  • selectmultiple
  • checbox
Read More

Improved Pickled Object Field

[Based on snippet #513 by obeattie.](http://www.djangosnippets.org/snippets/513/) **Update 10/10/09:** [Further development is now occurring on GitHub, thanks to Shrubbery Software.](http://github.com/shrubberysoft/django-picklefield) Incredibly useful for storing just about anything in the database (provided it is Pickle-able, of course) when there isn't a 'proper' field for the job. `PickledObjectField` is database-agnostic, and should work with any database backend you can throw at it. You can pass in any Python object and it will automagically be converted behind the scenes. You never have to manually pickle or unpickle anything. Also works fine when querying; supports `exact`, `in`, and `isnull` lookups. It should be noted, however, that calling `QuerySet.values()` will only return the encoded data, not the original Python object. *Please note that this is supposed to be two files, one fields.py and one tests.py (if you don't care about the unit tests, just use fields.py).* This PickledObjectField has a few improvements over the one in [snippet #513](http://www.djangosnippets.org/snippets/513/). 1. This one solves the `DjangoUnicodeDecodeError` problem when saving an object containing non-ASCII data by base64 encoding the pickled output stream. This ensures that all stored data is ASCII, eliminating the problem. 2. `PickledObjectField` will now optionally use `zlib` to compress (and uncompress) pickled objects on the fly. This can be set per-field using the keyword argument "compress=True". For most items this is probably **not** worth the small performance penalty, but for Models with larger objects, it can be a real space saver. 3. You can also now specify the pickle protocol per-field, using the protocol keyword argument. The default of `2` should always work, unless you are trying to access the data from outside of the Django ORM. 4. Worked around a rare issue when using the `cPickle` and performing lookups of complex data types. In short, `cPickle` would sometimes output different streams for the same object depending on how it was referenced. This of course could cause lookups for complex objects to fail, even when a matching object exists. See the docstrings and tests for more information. 5. You can now use the `isnull` lookup and have it function as expected. A consequence of this is that by default, `PickledObjectField` has `null=True` set (you can of course pass `null=False` if you want to change that). If `null=False` is set (the default for fields), then you wouldn't be able to store a Python `None` value, since `None` values aren't pickled or encoded (this in turn is what makes the `isnull` lookup possible). 6. You can now pass in an object as the default argument for the field without it being converted to a unicode string first. If you pass in a callable though, the field will still call it. It will *not* try to pickle and encode it. 7. You can manually import `dbsafe_encode` and `dbsafe_decode` from fields.py if you want to encode and decode objects yourself. This is mostly useful for decoding values returned from calling `QuerySet.values()`, which are still encoded strings. The tests have been updated to match the added features, but if you find any bugs, please post them in the comments. My goal is to make this an error-proof implementation. **Note:** If you are trying to store other django models in the `PickledObjectField`, please see the comments for a discussion on the problems associated with doing that. The easy solution is to put django models into a list or tuple before assigning them to the `PickledObjectField`. **Update 9/2/09:** Fixed the `value_to_string` method so that serialization should now work as expected. Also added `deepcopy` back into `dbsafe_encode`, fixing #4 above, since `deepcopy` had somehow managed to remove itself. This means that lookups should once again work as expected in **all** situations. Also made the field `editable=False` by default (which I swear I already did once before!) since it is never a good idea to have a `PickledObjectField` be user editable.

  • model
  • db
  • orm
  • database
  • pickle
  • object
  • field
  • type
  • pickled
  • store
Read More

Facebook event selector field

Ripped this out of a project I'm working on. The field renders as two <select> elements representing the two-level hierarchy organized events Facebook uses. Returns the id's Facebook wants.

  • forms
  • field
  • widget
  • facebook
  • fbml
  • fbjs
Read More

EmailListField for Django

A simple Django form field which validates a list of emails. [See this at my blog](http://sciyoshi.com/blog/2009/aug/08/emaillistfield-django/)

  • fields
  • forms
  • email
  • form
  • field
  • email-list
Read More

UsernameField (for clean error messages)

This is a username field that matches (and slightly tightens) the constraints on usernames in Django's `User` model. Most people use RegexField, which is totally fine -- but it can't provide the fine-grained and user friendly messages that come from this field.

  • fields
  • forms
  • user
  • auth
  • form
  • field
  • username
  • users
  • authorization
Read More

Base64Field: base64 encoding field for storing binary data in Django TextFields

This Base64Field class can be used as an alternative to a BlobField, which is not supported by Django out of the box. The base64 encoded data can be accessed by appending _base64 to the field name. This is especially handy when using this field for sending eMails with attachment which need to be base64 encoded anyways. **Example use:** class Foo(models.Model): data = Base64Field() foo = Foo() foo.data = 'Hello world!' print foo.data # will 'Hello world!' print foo.data_base64 # will print 'SGVsbG8gd29ybGQh\n'

  • django
  • model
  • field
  • base64
  • blob
  • base64field
Read More

CategoriesField

If you have a relatively small finite number of categories (e.g. < 64), don't want to add a separate column for each one, and don't want to add an entire separate table and deal with joins, this field offers a simple solution. You initialize the field with a list of categories. The categories can be any Python object. When saving a set of categories, the field converts the set to a binary number based on the indices of the categories list you passed in. So if you pass in as your categories list [A,B,C,D] and set model.categories = [C,D], the integer stored in the database is 0b1100 (note that although the categories list has a left-to-right index, the binary number grows right-to-left). This means that if you change the order of your category list once you have data in the DB, you'll need to migrate the data over to the new format. Adding items to the list should be fine however. If you need to do filtering based on this field, you can use bitwise operators. Django currently (to my knowledge) doesn't support this natively, but most DBs have some bitwise operator support and you can use the extra function for now. For example, this query will select CheeseShop models that have the 'Gouda' in its cheeses field. `CheeseShop.objects.all().extra(where=['cheeses | %s = cheeses'], params=[CHEESES.index('Gouda')])`

  • field
  • categories
  • binary
Read More

Easy Form Structuring

With this, you can group form fields very easily. Since it does not create any html, you can use it not only to create fieldsets (with tables, lists, etc).

  • fieldset
  • form
  • field
  • grouping
  • structuring
Read More
Author: jug
  • -4
  • 3

136 snippets posted so far.