Login

Improved model select field for generic relationships

Author:
kratorius
Posted:
July 2, 2009
Language:
Python
Version:
1.0
Score:
2 (after 2 ratings)

Browse through the installed models using the content types framework. There are two difference in behavior with respect to the default field:

  1. if a model provides a translation for its name (e.g.: verbose_name and/or verbose_name_plural), it shows that rather than a raw model name
  2. allow to filter the models shown through the use of choice parameter

Example:

mbf = ModelBrowseField(choices=['User', 'Session'])

 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
31
32
33
class ModelBrowseField(forms.ChoiceField):
    """
    Browse through the installed models using the content types framework.
    There are two difference in behavior with respect to the default field:

      1. if a model provides a translation (e.g.: verbose_name and/or
         verbose_name_plural), we show that rather than a raw model name
      2. allow to filter the models shown
    """
    def __init__(self, choices=None, *args, **kwargs):
        from django.contrib.contenttypes.models import ContentType

        qs = ContentType.objects.all()
        if choices:
            # if there's a list of allowed models, filter the queryset
            choices = list(choices)

            # labels are all lowercase
            choices = [choice.lower() for choice in choices]
            qs = qs.filter(model__in=choices)

        choices = qs.values_list('id', 'name')

        # translate items (if available)
        newchoices = []
        for id, choice in choices:
            id, mclass = id, ContentType.objects.get(pk=id).model_class()
            if mclass:
                newchoices.append((id, mclass._meta.verbose_name))
        choices = newchoices

        choices.insert(0, ('', '---------'))
        super(ModelBrowseField, self).__init__(choices=choices, *args, **kwargs)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 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, 7 months ago

Comments

sberlotto (on July 2, 2009):

Wow! very good work !

#

Please login first before commenting.