Login

Tag "field"

Snippet List

Username form field

Use a `UserField` if you want to replace the usual select menu with a simple input field that only accepts valid user names. Should be easy to generalize for other models by passing a query set and the attribute name that represents the instance. Example: class Book(models.Model): owner = models.ForeignKey(User) class BookForm(forms.ModelForm): owner = UserField() class Meta: model = Book

  • user
  • form
  • field
  • username
  • textual
Read More
Author: sma
  • 1
  • 2

FixedCharField and related

FixedCharField is used similarly to CharField, but takes a length attribute, and will only accept strings with that exact length. class Student(models.Model): student_id = FixedCharField(length=8) It currently only supports mysql, sqlite3, and oracle. The port to postgresql should be straightforward but I'm not sure about it so I haven't added it yet. This is a copy-paste (plus a couple of adaptations) from my project Chango, found at http://launchpad.net/chango/, so in order to keep up with latest updates it might be a good idea to use code directly from there.

  • field
  • form-field
  • fixed-length
Read More

Tamper safe HiddenFields

This snippet prevents people from tampering with the data in hidden form fields. This is something you usually want unless you have some Javascript Vodoo going on on the browser side. For the people scratching their heads: This form class will dynamically create a clean function for every passed additional hidden field, which just returns the original value of the hidden field. So the data in the hidden field posted gets actually ignored when calling the (overwritten) clean_{field name} function. This class is just an example using the protected hidden field feature for all passed field variables, which is probably not what you want. You have to add the editable fields the end of the __init__ function in the class. Example: `self.fields['bestbeer'] = forms.CharField(max_length=23)`

  • newforms
  • field
  • hidden
  • froms
Read More

MarkupTextField

I updated [MarkdownTextField](http://www.djangosnippets.org/snippets/882/) to have some choices in markup. It currently support for Markdown, Textile, Plain Text, and Plain HTML. It will add `%s_html` for the complied HTML and `%s_markup_choices` for a drop down of markup choices. Usage: class MyModel(models.Model): description = MarkupTextField()

  • model
  • markup
  • markdown
  • textile
  • field
Read More

FieldAccessForm (per-field user access for forms derived from models)

=== version 2 === > Parts of this code are based off of source from *davidcramer* on #django and I'd like to thank him for his assistance. Example: # forms.py ... class ForumPostForm(FieldAccessForm): class Meta: model = ForumPost class FieldAccess: moderator = FieldAccessLevel( lambda user, instance: user.get_profile().is_moderator, enable = ('approve', 'delete', 'edit') member = FieldAccessLevel( lambda user, instance: user.is_active, enable = ('edit',), exclude = ('approve', 'delete') ... # template ... <form action="" method="POST"> <table> {% for field in form %} <tr><th>{{ field.label_tag }}</th><td> {% if not field.field.disabled %} {{ field }} {% else %} {{ field.field.value }} {% endif %} </td></tr> {% endfor %} </table> <p><input type="submit" value="Update" /></p> </form> ... This class will grant or deny access to individual fields according to simple rules. The first argument must be a user object, but otherwise, this class is instantiated the same as a ModelForm. To utilize this code, inherit your form from FieldAccessForm, and create an inner class on your form called FieldAccess. Variables added to this inner class must have the same structure as that provided by the FieldAccessLevel class, which defines an access level, and the fields which apply to that access level. FieldAccessLevel takes as it's first argument a callable rule that validates this access level. That rule will be called with two arguments: 'user' (current user requesting access) and 'instance' (model instance in question). The keyword arguments to FieldAccessLevel are field groups which are used to determine which fields on this form are to be enabled and/or excluded, when the current user matches this access level. The term exclude indicates fields which are not to be rendered in the form at all. Any fields not grouped in either 'enable' or 'exclude' will be disabled by default. Superusers are always assumed to have full access. Otherwise, if a field is not specified with the FieldAccess inner class, then it is disabled by default. In other words, all users (except superusers) are denied access to all fields, unless they are specifically given access on a per-field basis. It is worth mentioning that multiple access levels can apply simultaneously, giving a user access to fields from all levels for which he matches the rule. If a user is denied access to a field, then the widget for that field is flagged as disabled and readonly. The field is also given two new attributes: a boolean 'disabled', and a 'value' containing the instanced model field. These two attributes allow a template author to have great control over the display of the form. For example, she may render the plain text value of a field instead of the disabled widget. The FieldAccess inner class also allows one to conditionally exclude fields from being rendered by the form. These exclusions operate very similarly to the standard Meta exclude option, except that they apply only to the access level in question. Note: The FieldAccess inner class may be used on both the form and the model; however, generally it makes more sense on the form. If you do use FieldAccess on both the form and model, be aware that both definitions will apply simultaneously. All access levels for which the user passes the rule will be processed, regardless of whether they were found on the form or the model.

  • form
  • field
  • permission
  • modelform
  • access
Read More

RangeField and RangeWidget

These field and widget are util for to those fields where you can put a star and end values. It supports most of field types and widgets (tested with IntegerField, CharField and DateField / TextInput and a customized DateInput). **Example of use:** class FormSearch(forms.Form): q = forms.CharField(max_length=50, label=_('Search for')) price_range = RangeField(forms.IntegerField, required=False) **Example of use (with forced widget):** class FormSearch(forms.Form): q = forms.CharField(max_length=50, label=_('Search for')) price_range = RangeField(forms.IntegerField, widget=MyWidget)

  • forms
  • field
  • widget
  • range
Read More

Encryption Fields

This provides some basic cryptographic fields using pyCrypto. All encryption/decription is done transparently and defaults to use AES. Example usage: class DefferredJunk(models.Model): semi_secret = EncryptedCharField(max_length=255)

  • model
  • field
  • encryption
Read More

Alternative to Captchas (Without Human Interaction)

This security field is based on the perception that spambots post data to forms in very short or very long regular intervals of time, where it takes reasonable time to fill in a form and to submit it for human beings. Instead of captcha images or Ajax-based security interaction, the SecurityField checks the time of rendering the form, and the time when it was submitted. If the interval is within the specific range (for example, from 5 seconds till 1 hour), then the submitter is considered as a human being. Otherwise the form doesn't validate. Usage example: class TestForm(forms.Form): prevent_spam = SecurityField() # ... other fields ... The concept works only for unbounded forms.

  • captcha
  • security
  • form
  • field
  • antispam
  • antibot
Read More

Integer Currency Input

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
Read More

Replace model select widget in admin with a readonly link to the related object

This replaces the html select box for a foreign key field with a link to that object's own admin page. The foreign key field (obviously) is readonly. This is shamelessly based upon the [Readonly admin fields](http://www.djangosnippets.org/snippets/937/) snippet. However, that snippet didn't work for me with ForeignKey fields. from foo.bar import ModelLinkAdminFields class MyModelAdmin(ModelLinkAdminFields, admin.ModelAdmin): modellink = ('field1', 'field2',)

  • admin
  • field
  • widget
  • readonly
  • modelchoicefield
Read More

auto image field w/ prepopulate_from & default

Given such code: class ProductImage(models.Model): fullsize = models.ImageField(upload_to= "products/%Y/%m/%d/") display = AutoImageField(upload_to= "products/%Y/%m/%d/",prepopulate_from='fullsize', size=(300, 300)) thumbnail = AutoImageField(upload_to="products/%Y/%m/%d/",null=True,default='/media/noimage.jpg')) display will be automatically resized from fullsize, and thumbnail will default to /media/noimage.jpg if no image is uploaded Note: At some point the code broke against trunk, which has now been updated to work properly

  • image
  • models
  • db
  • field
Read More

Smarter USPhoneNumberField

The original USPhoneNumberField only validates xxx-xxx-xxxx values. This field validates... > (xxx) xxx xxxx > xxx-xxx-xxxx > (xxx)-xxx-xxxx > many others. **Explanation of the regular expression:** 1. Accepts either (xxx) or xxx at the start of the value. 2. Allows for any amount of dashes and spaces (including none) before the next set of digits. 3. Accepts 3 digits 4. Allows for any amount of dashes and spaces (including none) before the next set of digits. 5. Accepts 4 digits, finishing the value. This field saves in the same format that the original USPhoneNumberField does (xxx-xxx-xxxx). Enjoy!

  • forms
  • validation
  • field
  • phone
Read More

Readonly admin fields

Put this code and import it where you define your ModelAdmin-classes. # typical admin.py file: from django.contrib import admin from foo.bar import ReadOnlyAdminFields class MyModelAdmin(ReadOnlyAdminFields, admin.ModelAdmin): readonly = ('field1', 'field2',)

  • django
  • admin
  • field
  • readonly
Read More

change a widget attribute in ModelForm without define the field

I will change a model form widget attribute without define the complete field. Because many "meta" information are defined in the model (e.g. the help_text) and i don't want to repeat this. I found a solution: Add/change the widget attribute in the __init__, see example code.

  • newforms
  • forms
  • field
  • modelform
Read More

PositionField

**This is a model field for managing user-specified positions.** Usage ===== Add a `PositionField` to your model; that's just about it. If you want to work with all instances of the model as a single collection, there's nothing else required. In order to create collections based on another field in the model (a `ForeignKey`, for example), set `unique_for_field` to the name of the field. It's probably also a good idea to wrap the `save` method of your model in a transaction since it will trigger another query to reorder the other members of the collection. Here's a simple example: from django.db import models, transaction from positions.fields import PositionField class List(models.Model): name = models.CharField(max_length=50) class Item(models.Model): list = models.ForeignKey(List, db_index=True) name = models.CharField(max_length=50) position = PositionField(unique_for_field='list') # not required, but probably a good idea save = transaction.commit_on_success(models.Model.save) Indices ------- In general, the value assigned to a `PositionField` will be handled like a list index, to include negative values. Setting the position to `-2` will cause the item to be moved to the second position from the end of the collection -- unless, of course, the collection has fewer than two elements. Behavior varies from standard list indices when values greater than or less than the maximum or minimum positions are used. In those cases, the value is handled as being the same as the maximum or minimum position, respectively. `None` is also a special case that will cause an item to be moved to the last position in its collection. Limitations =========== * Unique constraints can't be applied to `PositionField` because they break the ability to update other items in a collection all at once. This one was a bit painful, because setting the constraint is probably the right thing to do from a database consistency perspective, but the overhead in additional queries was too much to bear. * After a position has been updated, other members of the collection are updated using a single SQL `UPDATE` statement, this means the `save` method of the other instances won't be called. More === More information, including an example app and tests, is available on [Google Code](http://code.google.com/p/django-positions/).

  • lists
  • models
  • fields
  • model
  • field
  • list
  • sorting
  • ordering
  • collection
  • collections
Read More

136 snippets posted so far.