Login

Tag "field"

Snippet List

CountryField (ISO 3166-1)

List of countries based on the ISO 3166-1 standard. List adapated from http://opencountrycodes.appspot.com/python/ This is useful for certain services such as Protx that requires countries in the two letter standard.

  • field
  • country
  • custom-field
  • iso-3166-1
  • protx
Read More

MultipleEmailsField

This is a custom field for multiple emails separated by comma. Original code was replaced by code from Django documentation: http://docs.djangoproject.com/en/dev/ref/forms/validation/ (MultiEmailField) so i'm not the author of the code, but just put it here to replace an outdated solution. Uses code from mksoft comment http://www.djangosnippets.org/snippets/1093/

  • multiple
  • forms
  • email
  • field
Read More

Tuned IPAddressField with IPv4 & IPv6 support using Postgres Network Field type

I wanted to store ipv4 and ipv6 ip's in django but I wanted to use the postgresql inet network field type: http://www.postgresql.org/docs/8.3/static/datatype-net-types.html and I wanted to use IPy.py IP objects in python. I followed these very helpful examples along with the django documentation: http://vaig.be/2009/03/numeric-ip-field-for-django.html http://www.djangosnippets.org/snippets/1381/ It took me awhile to figure out how this works (not that I completely understand it now..) and figured I would share it. If anyone finds problems with this or can make it better I will definitely use it.

  • model
  • field
  • ip
  • custom
  • ip-address
  • ip-addresses
  • ipv4
  • ipv6
  • ipy
  • postgresql-network-field
Read More

"Dynamic" form with a hidden field

This code demonstrates two simple techniques: 1. so-called "dynamic" forms, in which the form is created at run time by the model 2. using a widget (forms.widgets.HiddenInput) for a field of the form. I feel like this could be highlighted more in the documentation. You need to do something similar to get a textarea (forms.CharField(widget=forms.widgets.Textarea()) and it took me too long to figure this out. There are, no doubt, good reasons not to do what I'm doing here the way I'm doing it. Peanut gallery?

  • dynamic
  • form
  • field
  • hidden
Read More

Readonly fields on Form/Modelform

A Form and ModelForm which provides the ability to specify certain fields as readonly, meaning that they will display their value as text wrapped with a <span> tag. The user is unable to edit them, and they are protected from POST data insertion attacks. The recommended usage is to place a NewMeta inner class on the form, with a readonly attribute which is a list or tuple of fields, similar to the fields and exclude attributes on the Meta inner class. class MyForm(ReadonlyForm): foo = forms.TextField() bar = forms.TextField() class NewMeta: readonly = ('foo',) Use these forms as you would a standard form in your templates.

  • forms
  • field
  • readonly
  • modelforms
  • span
Read More

MAC address field

Supported MAC formats: aa:bb:cc:dd:ee:ff, separator : or - aabbccddeeff both lower case and upper case

  • model
  • field
  • custom-field
  • address
  • mac
Read More

NonceField for disabling autocompletion

For disabling autocomplete and security purpose, this snippet defines a CharField with a randomness name for each request of the form. This is useful for turning off autocomplete for credit card input in all browsers, without breaking the xhtml validation. * [https://wiki.mozilla.org/The_autocomplete_attribute_and_web_documents_using_XHTML#Security](https://wiki.mozilla.org/The_autocomplete_attribute_and_web_documents_using_XHTML#Security) * [http://en.wikipedia.org/wiki/Cryptographic_nonce](http://en.wikipedia.org/wiki/Cryptographic_nonce)

  • fields
  • forms
  • validation
  • security
  • form
  • field
  • autocomplete
  • formfield
  • nonce
Read More

ManyToManyField no syncdb

**Sumary** M2M relation without creating table. Normally you should specify m2m only in *one* model, thus widgets for many-to-many relations will be displayed inline on whichever model contains the actual reference to the ManyToManyField. But if you want to be able to have widgets displayed on both form you need some tricks, for example using intermediary-models can help, but you will not get multiselect widget (and in case of inlining extra = multi). Also you can write your own form which takes care about adding widget (just 1 line) and setting default values and saving it (more than few lines of code). If you try ManyToManyField with same db_table specified, the only problem will be in syncdb (it will try to create two identical tables) and the only thing our class does is preventing creation of table for M2M, so in one model you should use ManyToManyField and in another ManyToManyField_NoSyncdb with the same db_table argument. **Example** So to have M2M widgets in both forms you can write: class User(models.Model): #... groups = ManyToManyField('Group', related_name='groups', db_table=u'USERS_TO_GROUPS') class Group(models.Model): #... users = ManyToManyField_NoSyncdb(User, related_name='users', db_table=u'USERS_TO_GROUPS')

  • model
  • field
  • manytomany
  • manytomanyfield
  • syncdb
Read More

CountryField (UN Country List, 3 Char Codes)

**Adapted from** [CountryField](http://www.djangosnippets.org/snippets/494/) - **Initial thanks to marinho** Uses the UN country list listed in the source - this provides the 3 character ISO country code. Ordered by display value and not country code. Just place anywhere you like and import CountryField to use. `country = CountryField(verbose_name="Country", help_text="The registrant's country of residence.")`

  • forms
  • form
  • field
  • list
  • country
  • countries
  • custom
  • custom-field
  • countryfield
  • countrys
Read More
Author: djm
  • 1
  • 1

uuid model field

This code provides a primary key field that is globally unique. It uses the pre_save method to auto-populate the field with a Universal Unique Id as the record is saved the first time.

  • model
  • field
  • uuid
  • universally-unique-identifier
Read More

ImageWithThumbsField

Easy way to generate image thumbnails for your models. Works with any Storage Backend. From: [http://code.google.com/p/django-thumbs/](http://code.google.com/p/django-thumbs/) **Usage example:** ============== photo = ImageWithThumbsField(upload_to='images', sizes=((125,125),(300,200),) To retrieve image URL, exactly the same way as with ImageField: my_object.photo.url To retrieve thumbnails URL's just add the size to it: my_object.photo.url_125x125 my_object.photo.url_300x200 Note: The 'sizes' attribute is not required. If you don't provide it, ImageWithThumbsField will act as a normal ImageField **How it works:** ============= For each size in the 'sizes' atribute of the field it generates a thumbnail with that size and stores it following this format: available_filename.[width]x[height].extension Where 'available_filename' is the available filename returned by the storage backend for saving the original file. Following the usage example above: For storing a file called "photo.jpg" it saves: photo.jpg (original file) photo.125x125.jpg (first thumbnail) photo.300x200.jpg (second thumbnail) With the default storage backend if photo.jpg already exists it will use these filenames: photo_.jpg photo_.125x125.jpg photo_.300x200.jpg **Note:** It assumes that if filename "any_filename.jpg" is available filenames with this format "any_filename.[widht]x[height].jpg" will be available, too.

  • image
  • models
  • fields
  • thumbnail
  • field
  • thumbnails
  • thumbs
Read More

Friendly ID

Invoice numbers like "0000004" are a little unprofessional in that they expose how many sales a system has made, and can be used to monitor the rate of sales over a given time. They are also harder for customers to read back to you, especially if they are 10 digits long. This is simply a perfect hash function to convert an integer (from eg an ID AutoField) to a unique number. The ID is then made shorter and more user-friendly by converting to a string of letters and numbers that wont be confused for one another (in speech or text). To use it: import friendly_id class MyModel(models.Model): invoice_id = models.CharField(max_length=6, null=True, blank=True, unique=True) def save(self, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) # Populate the invoice_id if it is missing if self.id and not self.invoice_id: self.invoice_id = friendly_id.encode(self.id) super(MyModel, self).save(*args, **kwargs) if self.id and not self.invoice_id When an object from this model is saved, an invoice ID will be generated that does not resemble those surrounding it. For example, where you are expecting millions of invoices the IDs generated from the AutoField primary key will be: obj.id obj.invoice_id 1 TTH9R 2 45FLU 3 6ACXD 4 8G98W 5 AQ6HF 6 DV3TY ... 9999999 J8UE5 The functions are deterministic, so running it again sometime will give the same result, and generated strings are unique for the given range (the default max is 10,000,000). Specifying a higher range allows you to have more IDs, but all the strings will then be longer. You have to decide which you need: short strings or many strings :-) This problem could have also been solved using a random invoice_id generator, but that might cause collisions which cost time to rectify, especially when a decent proportion of the available values are taken (eg 10%). Anyhow, someone else has now already written this little module for you, so now you don't have to write your own :-)

  • field
  • id
Read More

UKPhoneNumberField

Validates and cleans UK telephone numbers. Number length is checked, and numbers are cleaned into a common format. For example, "+44 (0)1234 567890" will be stored as "01234 567890" Can reject premium numbers (09123 123123) or service numbers (1471, 118 118) with `UKPhoneNumberField(reject=('premium', 'service'))` Uses info from [Wikipedia](http://en.wikipedia.org/wiki/Telephone_numbers_in_the_United_Kingdom)

  • form
  • field
  • uk
  • localflavor
Read More

136 snippets posted so far.