Login

Select multiple using a manytomany checkbox

Author:
fivethreeo
Posted:
November 22, 2007
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

Usage:

from yourapp.fields import CheckBoxManyToMany
from django.db import models

class Weekday(models.Model):
    name = models.CharField()

    def __unicode__(self):
        return self.name

class EventWithWeekday(models.Model):
    weekdays = CheckBoxManyToMany(Weekday)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from django import oldforms
from django.db import models
from django.utils.functional import curry

class CheckBoxManyToMany(models.ManyToManyField):
    def get_manipulator_field_objs(self):
        if self.rel.raw_id_admin:
            return [oldforms.RawIdAdminField]
        else:
            choices = self.get_choices_default()
            return [curry(oldforms.CheckboxSelectMultipleField, choices=choices)]

    def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True):
        """
        Returns a list of oldforms.FormField instances for this field. It
        calculates the choices at runtime, not at compile time.

        name_prefix is a prefix to prepend to the "field_name" argument.
        rel is a boolean specifying whether this field is in a related context.
        """
        field_objs, params = self.prepare_field_objs_and_params(manipulator, name_prefix)

        # BooleanFields (CheckboxFields) are a special case. They don't take
        # is_required.
        if 'is_required' in params:
            del params['is_required']

        # Finally, add the field_names.
        field_names = self.get_manipulator_field_names(name_prefix)
        return [man(field_name=field_names[i], **params) for i, man in enumerate(field_objs)]

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

statico (on March 6, 2009):

I'd love to see a newforms implementation of this.

#

Please login first before commenting.