Login

Tag "fields"

Snippet List

MarkupField

This is a field that allows multiple markup types but also stores the pre-rendered result in the database which offers an advantage over calling one of the render methods each time. Example usage looks like: class BlogPost(models.Model): ... post = MarkupField() the various extra fields can then be accessed as follows: BlogPost.objects.get(pk=1).post # raw content BlogPost.objects.get(pk=1).post_markup_type # markup type (plain text, html, markdown, rest, textile) BlogPost.objects.get(pk=1).post_rendered # content of post rendered to html BlogPost.objects.get(pk=1).post_as_html # property that access post_rendered but marked safe for easy use in templates After writing my initial version of this I was pointed at the similar http://www.djangosnippets.org/snippets/1169/ I find mine a bit more useful as it includes ReST and includes a mark_safe call to allow showing the rendered HTML directly. I have however borrowed the nice idea of dynamically building MARKUP_TYPES from #1169. Also available via http://gist.github.com/67724.

  • fields
  • rest
  • markup
  • markdown
  • textile
  • restructuredtext
Read More
Author: jpt
  • 8
  • 16

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

Form splitting/Fieldset templatetag

Syntax: `{% get_fieldset list,of,fields as new_form_object from original_form %}` Example: {% load fieldsets %} ... <fieldset id="contact_details"> <legend>Contact details</legend> <ul> {% get_fieldset first_name,last_name,email,cell_phone as personal_fields from form %} {{ personal_fields.as_ul }} </ul> </fieldset> <fieldset> <legend>Address details</legend> <ul> {% get_fieldset street_address,post_code,city as address_fields from form %} {{ address_fields.as_ul }} </ul> </fieldset>

  • fields
  • forms
  • fieldset
Read More

Ajax form with jQuery

I recently got a form working via jQuery and Django. This was not easy for me to do and I thought I'd record my finding here. The form submits via jQuery and the "form" plugin. Please visit jQuery's home page to find all those links. This code handles: * urls.py -- passing both normal and 'Ajax' urls to a view. * views.py -- Handling both kinds of requests so that both normal and ajax submits will work. * The HTML template with the script for submitting and some bling. Error handling === I like to stay DRY so the idea of checking the form for errors in javascript *and* checking it in Django irks me. I decided to leave that up to Django, so the form submits and gets validated on the server. The error messages are sent back to the browser and then displayed.

  • ajax
  • urls
  • fields
  • views
  • jquery
  • form
  • errors
Read More

CustomImageField for Django 1.0 alpha

The venerable CustomImageField, invented by [Scott Barnham](http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/) and rejiggered for newforms-admin by [jamstooks](http://pandemoniumillusion.wordpress.com/2008/08/06/django-imagefield-and-filefield-dynamic-upload-path-in-newforms-admin/#comments). This here is a stab at a [post-Signals-refactor](http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges#Signalrefactoring) version. Seems to do 'er. Note: This should be pointless once [fs-refactor](http://code.djangoproject.com/ticket/5361) lands.

  • models
  • fields
  • imagefield
  • newforms-admin
  • signals
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

XFN Form Field

**This is a newforms field for XFN relationships.** It normalizes input by removing excess whitespace, converting to lowercase and removing duplicates. This field also validates the relationship according to the [XFN profile](http://gmpg.org/xfn/11): `me` can only appear by itself and, at most, one value from each of the family, friendship and geographical categories is allowed. The `XFN_*` constants would probably be imported from somewhere else in practice, but are included here for simplicity.

  • newforms
  • fields
  • forms
  • form
  • field
  • xfn
Read More

OpenID Form Field

**This is a newforms field for OpenID 1 & 2.** It normalizes and validates OpenID identifiers according to the [spec](http://openid.net/specs/openid-authentication-2_0.html#normalization): * `xri://=joelwatts` to `=joelwatts` * `joelwatts.com` to `http://joelwatts.com/` * `www.joelwatts.com` to `http://joelwatts.com/` An identifier that is well-formed, but not an OpenID (e.g. `example.com`), will cause a validation error. Requires [Python OpenID Library](http://openidenabled.com/python-openid/) 2.x.x.

  • newforms
  • fields
  • forms
  • form
  • field
  • openid
  • openid2
  • inames
  • identity
Read More

Field map for models

It seems like one way or another I always need to get access to a specific field of a Model object. The current way to do this is to iterate through the object's _meta.fields list, comparing with the `name` attribute. Why not just have a lookup of fields? If you paste this code at the bottom of your models.py file it will add a `field_map` attribute to the meta options. For example: `profile = User.objects.get(id=1).get_profile()` `upload_to = profile._meta.field_map['image_icon'].upload_to` ...

  • models
  • fields
  • meta
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

ingore_fields

I use this snippet when creating newforms with form_for_model and form_for_instance. Both do not have an argument that lets you filter out fields easily so I wrote this instead. Typical use: `form_class = form_for_instance(obj, fields=ignore_fields(model_class, ['field_name1']))`

  • newforms
  • fields
  • ignore
Read More

51 snippets posted so far.