Login

ManyToManyFieldWithDefault

Author:
trbs
Posted:
June 1, 2008
Language:
Python
Version:
.96
Tags:
field sites manytomanyfield many default
Score:
2 (after 2 ratings)

Extension to the normal ManyToManyField to support default values.

Build for the following use case:

publish_on = ManyToManyFieldWithDefault(Site, verbose_name=_('publish on'), default=Site.objects.get_current)

Where with a plain ManyToManyField the default site will not be selected. The ManyToManyFieldWithDefault fixes this by automatically selecting the default value if no other selections are given.

When the field also have null=True and Blank=True it will not select the default !

 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
from django import oldforms
from django.db import models
from django.utils.functional import curry

class SelectMultipleFieldWithDefault(oldforms.SelectMultipleField):
    def __init__(self, default_choice=None, *args, **kwargs):
        self.__default_choice = default_choice
        super(SelectMultipleFieldWithDefault, self).__init__(*args, **kwargs)
        
    def render(self, data):
        if not data and self.__default_choice:
            data = [self.__default_choice.id]
        return super(SelectMultipleFieldWithDefault, self).render(data)

class ManyToManyFieldWithDefault(models.ManyToManyField):
    def __init__(self, *args, **kwargs):
        if not kwargs.get('blank', False) and not kwargs.get('null', False):
            self.__default_choice = kwargs.get('default', None)
        else:
            self.__default_choice = None
        super(ManyToManyFieldWithDefault, self).__init__(*args, **kwargs)
        
    def get_manipulator_field_objs(self):
        if self.rel.raw_id_admin:
            return [oldforms.RawIdAdminField]
        else:
            choices = self.get_choices_default()
            return [curry(SelectMultipleFieldWithDefault, size=min(max(len(choices), 5), 15), choices=choices, default_choice=self.__default_choice)]

More like this

  1. Display user-friendly values of a ManyToManyRawIdWidget by luc_j 4 years, 8 months ago
  2. Preview tag for fields with choices by kmmbvnr 6 years, 11 months ago
  3. Javascript Chain Select Widget by ogo 6 years, 10 months ago
  4. Field value as plain text which can't be edited by user by szczavv 5 years, 6 months ago
  5. A ModelChoiceField with support for title in options based on a field in the model by celopes 4 years, 7 months ago

Comments

Please login first before commenting.