Login

Tag "field"

Snippet List

OwnerField

This is a little helper for associating an owner to a newly created object, in this case making the assumption that the current user is always the owner. It removes the necessity of adding a custom save hook to your model. get_current_user comes from this middleware trick to cache the current user: http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser

  • model
  • user
  • field
  • owner
  • ownerfield
Read More

BirthYearField

A form field to prompt for a year of birth with suitable sanity checks. Usage eg: yob = BirthYearField(label="What year were you born?")

  • form
  • field
  • year
  • birth
Read More

SeparatedValuesField

A Django newforms field which takes another newforms field during initialization and validates every item in a comma-separated list with this field class. Please use it like this: from django.newforms import EmailField emails = CommaSeparatedValuesField(EmailField) You would be able to enter a string like "[email protected],[email protected]" because every email address would be validated when clean() is executed. This of course also applies to any other Field class. You can define the sepator (default: ",") during initialization with the `separator` parameter like this: from django.newforms import EmailField` emails = SeparatedValuesField(EmailField, separator="###")

  • newforms
  • field
  • comma
  • separated
Read More

CountryField

**How to use** put this code somewhere you want, import CountryField and use

  • field
  • country
  • countries
Read More

AutoSlugField

This is a simple solution aimed at saving some time when you simply want to get a slug from a model field just before saving.

  • fields
  • slug
  • field
Read More

Update only selected model fields

Watch out! Previous versions of this snippet (without the values list) were vulnerable to SQL injection attacks. The "correct" solution is probably to wait until [ticket 4102](http://code.djangoproject.com/ticket/4102) hits the trunk. But here's my temporary fix while we wait for that happy day. Django's model.save() method is a PITA: 1. It does a SELECT first to see if the instance is already in the database. 2. It has additional database performance overhead because it writes all fields, not just the ones that have been changed. 3. It overwrites other model fields with data that may be out of date. This is a real problem in concurrent applications, like almost all web apps. If you just want to update a field or two on a model instance which is already in the database, try this: update_fields(user, email='[email protected]', is_staff=True, last_login=datetime.now()) Or you can add it to your models (see below) and then do this: user.update_fields( email='[email protected]', is_staff=True, last_login=datetime.now()) To add it to your model, put it in a module called granular_update, then write this in your models.py: import granular_update class User(models.Model): email = models.EmailField() is_staff = models.BooleanField() last_login = models.DateTimeField() update_fields = granular_update.update_fields

  • fields
  • model
  • save
  • performance
  • field
  • update
  • integrity
  • consistency
Read More

mark a required field by "*" in a template

the trick resides in `field.field.required`. The intuitive way of testing this in the templates is to access `field.required`. But it's not the good one. Enjoy! [Found via Django users Google Groups](http://groups.google.com/group/django-users/browse_thread/thread/ce83f74fb1156b4b/0df36947de16a071?lnk=gst&q=required+field#0df36947de16a071)

  • newforms
  • forms
  • templates
  • field
  • required
Read More

FieldLevelPermissionsAdmin

Have you ever needed to customize permissions, for example, allow only some fields for editing by some group of users, display some fields as read-only, and some to hide completely? FieldLevelPermissionsAdmin class does this for newforms-admin branch. Not tested well yet (>100 LOC!). You typically would like to use it this way: class MyObjectAdmin(FieldLevelPermissionsAdmin): def can_view_field(self, request, object, field_name): """ Boolean method, returning True if user allowed to view field with name field_name. user is stored in the request object, object is None only if object does not exist yet """ ...your code... def can_change_field(self, request, object, field_name): """ Boolean method, returning True if user allowed to change field with name field_name. user is stored in the request object, object is None only if object does not exist yet """ ...your code... def queryset(self, request): """ Method of ModelAdmin, override it if you want to change list of objects visible by the current user. """ mgr = self.model._default_manager if request.user.is_superuser: return mgr.all() filters = Q(creator=request.user)|Q(owner=request.user) return mgr.filter(filters)

  • newforms
  • admin
  • field
  • permissions
  • workflow
  • customize
  • customization
  • field-level
  • row
Read More

ImageURLField for forms

A URL field specifically for images, which can validate details about the filesize, dimensions and format of an image at a given URL, without having to read the entire image into memory. Requires [Python Imaging Library](http://www.pythonware.com/library/pil/). *4th October, 2008* - updated for 1.0 compatibility.

  • image
  • pil
  • validation
  • url
  • form
  • field
Read More

Drop down Datefield

Simple drop-down date field for use. You can specify date range by initiating new DateDropdownWidget. Welcome comments!

  • newforms
  • forms
  • dropdown
  • datefield
  • field
Read More

UTC DateTime field

A DateTime field extension that automatically stores the timezone, and the computed UTC equivalent. This field needs the pytz library. The field adds two new fields to the model, with the same name of the UTCDateTimeField field, and a suffix. For an UTCDateTimeField named 'updated', the model will contain * an 'updated' field, which holds the local datetime * an 'updated_utc' field, which holds the corresponding UTC datetime * an 'updated_tz' field, which holds the field timezone name The timezone can vary between model instances, just set the 'xxx_tz' field to the desired timezone before saving. UTCDateTimeField supports a single optional keyword argument 'default_tz', in addition to the DateTimeField standard ones, to let the user choose a provider for a default timezone when no timezone has been set. Its value can be * None (or the argument missing), in which case the default settings.TIME_ZONE will be used * a callable, which will be called when the 'xxx_tz' field is emtpy, which should return a timezone name * a string, which will be used to access a model attribute or call a model method, which should return a timezone name If the timezone name points to a non-existent timezone, a warning will be issued and the default settings.TIME_ZONE value will be used. The field will also add three properties to the model, to access the pytz timezone instance, and the offset aware datetimes for local time and UTC. For the same 'updated' field instance we used above, the three properties added to the model will be: * updated_timezone * updated_offset_aware * updated_utc_offset_aware A brief example on how to use UTCDateTimeField: class UTCDateTimeTest(models.Model): """ >>> import datetime >>> d = datetime.datetime(2007, 8, 24, 16, 46, 34, 762627) # new instance, tz from model method >>> t = UTCDateTimeTest(updated=d) >>> t.save() >>> t.updated datetime.datetime(2007, 8, 24, 16, 46, 34, 762627) >>> t.updated_utc datetime.datetime(2007, 8, 24, 14, 46, 34, 762627) >>> t.updated_tz 'Europe/Rome' >>> t.updated_timezone <DstTzInfo 'Europe/Rome' CET+1:00:00 STD> >>> t.updated_offset_aware datetime.datetime(2007, 8, 24, 16, 46, 34, 762627, tzinfo=<DstTzInfo 'Europe/Rome' CEST+2:00:00 DST>) >>> t.updated_utc_offset_aware datetime.datetime(2007, 8, 24, 14, 46, 34, 762627, tzinfo=<UTC>) >>> """ updated = UTCDateTimeField(default_tz='get_tz') def get_tz(self): return 'Europe/Rome'

  • models
  • fields
  • datetime
  • timezone
  • field
  • utc
Read More

CompressedTextField

A CompressedTextField to transparently save data gzipped in the database and uncompress at retrieval. Full description at my blog: [arnebrodowski.de/...Field-for-Django.html](http://www.arnebrodowski.de/blog/435-Implementing-a-CompressedTextField-for-Django.html)

  • text
  • model
  • field
  • compressed
Read More

JSONField

This is a great way to pack extra data into a model object, where the structure is dynamic, and not relational. For instance, if you wanted to store a list of dictionaries. The data won't be classically searchable, but you can define pretty much any data construct you'd like, as long as it is JSON-serializable. It's especially useful in a JSON heavy application or one that deals with a lot of javascript. **Example** (models.py): from django.db import models from jsonfield import JSONField class Sequence(models.Model): name = models.CharField(maxlength=25) list = JSONField() **Example** (shell): fib = Sequence(name='Fibonacci') fib.list = [0, 1, 1, 2, 3, 5, 8] fib.save() fib = Sequence.objects.get(name='Fibonacci') fib.list.append(13) print fib.list [0, 1, 1, 2, 3, 5, 8, 13] fib.get_list_json() "[0, 1, 1, 2, 3, 5, 8, 13]" *Note:* You can only save JSON-serializable data. Also, dates will be converted to string-timestamps, because I don't really know what better to do with them. Finally, I'm not sure how to interact with forms yet, so that realm is a bit murky.

  • models
  • model
  • json
  • db
  • field
  • json-field
Read More

UUIDField

UUIDField is a field which stores an uuid generated by pythons new uuid module. it's included with the python 2.5 distribution by default, but if you run an older version of python you can happily copy the file from 2.5 to django/utils/uuid.py or your project directory.

  • fields
  • field
  • uuid
Read More

136 snippets posted so far.