ModelMixin

 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
##############
#  utils.py  #
##############

class MixinType(type):
    def __new__(cls, name, bases, dct):
        ret = type.__new__(cls, name, bases, dct)

        if name != 'ModelMixin':
            assert 'model' in dct
            model = dct.pop('model')

            for k, v in dct.iteritems():
                if k not in ModelMixin.__dict__:
                    model.add_to_class(k, v)

        return ret


class ModelMixin(object):
    __metaclass__ = MixinType


###############
#  models.py  #
###############

class UserMixin(ModelMixin):
    model = User

    @property
    def foobar(user):
        try:
            return user.foobar_set.get()
        except Foobar.DoesNotExist:
            return None

    @property
    def is_boss(user):
        return user.foobar is not None

    def __unicode__(user):
        try:
            profile = user.get_profile()
            if profile.full_name:
                return profile.full_name

        except UserProfile.DoesNotExist:
            pass

        full_name = (u'%s %s' % (user.first_name, user.last_name)).strip()
        if full_name:
            return full_name

        return user.username

    def get_absolute_url(user):
        return reverse('localsite_user_detail', kwargs=dict(username=user.username))

More like this

  1. Automatic Manager Choice Filters by nipuL 5 years, 2 months ago
  2. Get derived model instance by werehuman 7 months ago
  3. Flatpage Suggester Template tag for 404 templates by bradmontgomery 4 years, 2 months ago
  4. Humanize lists of strings in templates by ChipX86 6 years, 10 months ago
  5. Make tags easier with properties by ubernostrum 7 years, 1 month ago

Comments

(Forgotten your password?)