~panosl/+junk/django-attachments

« back to all changes in this revision

Viewing changes to attachments/templatetags/attachments_tags.py

  • Committer: Panos Laganakos
  • Date: 2011-10-06 07:31:43 UTC
  • Revision ID: panos@phaethon-designs.gr-20111006073143-wmml8s14b39q489y
ability to limit uploads per model object.

Show diffs side-by-side

added added

removed removed

Lines of Context:
93
93
        'obj': next_bit_for(bits, 'get_attachments_for'),
94
94
        'var_name': next_bit_for(bits, 'as', '"attachments"'),
95
95
    }
96
 
    return AttachmentsForObjectNode(**args)
 
 
b'\\ No newline at end of file'
 
96
    return AttachmentsForObjectNode(**args)
 
97
 
 
98
class AttachmentsSizeForObjectNode(Node):
 
99
    def __init__(self, obj, var_name):
 
100
        self.obj = obj
 
101
        self.var_name = var_name
 
102
 
 
103
    def resolve(self, var, context):
 
104
        """Resolves a variable out of context if it's not in quotes"""
 
105
        if var[0] in ('"', "'") and var[-1] == var[0]:
 
106
            return var[1:-1]
 
107
        else:
 
108
            return Variable(var).resolve(context)
 
109
 
 
110
    def render(self, context):
 
111
        MEGABYTE = 1048576.0
 
112
        obj = self.resolve(self.obj, context)
 
113
        var_name = self.resolve(self.var_name, context)
 
114
        context[var_name] = Attachment.objects.attachments_size_for_object(obj) / MEGABYTE
 
115
        return ''
 
116
 
 
117
 
 
118
@register.tag
 
119
def get_attachments_size_for(parser, token):
 
120
    def next_bit_for(bits, key, if_none=None):
 
121
        try:
 
122
            return bits[bits.index(key)+1]
 
123
        except ValueError:
 
124
            return if_none
 
125
 
 
126
    bits = token.contents.split()
 
127
    args = {
 
128
        'obj': next_bit_for(bits, 'get_attachments_size_for'),
 
129
        'var_name': next_bit_for(bits, 'as', '"attachments_size"'),
 
130
    }
 
131
    return AttachmentsSizeForObjectNode(**args)