Login

Comma separated users field

Author:
sopelkin
Posted:
February 13, 2008
Language:
Python
Version:
.96
Tags:
django newforms fields users
Score:
2 (after 2 ratings)

Easy comma separated users field. I use it take custom permission for some users.

 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
from django.newforms.fields import Field
from django.newforms.util import ValidationError 
from django.contrib.auth.models import User

from django.newforms.widgets import Input

class CommaSeparatedUsersInput(Input):
    input_type = 'text'
    
    def render(self, name, value, attrs=None):

        if value is None:
            value = ''
        elif isinstance(value, (list, tuple)):
            value = (', '.join([ user.username for user in value ]))
        return super(CommaSeparatedUsersInput, self).render(name, value, attrs)

class CommaSeparatedUsersField(Field):
    
    widget = CommaSeparatedUsersInput
    
    def clean(self, value):
        super(CommaSeparatedUsersField, self).clean(value)
        
        if not value:
            return ''
        
        if isinstance(value, (list, tuple)):
            return value

        names = set(value.lower().split(','))
        name_set = set([name.strip().lower() for name in names])
        users = list(User.objects.filter(username__in=name_set))
        unknown_names = name_set ^ set([user.username.lower() for user in users])
        if unknown_names:
            raise ValidationError('this names are incorrect %s ' % str(names))

        return users

More like this

  1. Newforms field for decimals with a comma by jonasvp 6 years, 11 months ago
  2. Many2Many comma separated form field by haloween 5 years ago
  3. (en-US) Humanized Decimal Field by ActionScripted 6 years, 8 months ago
  4. MultipleChoiceCommaField by rubic 8 years ago
  5. Multiple emails field by cuchac 9 months, 3 weeks ago

Comments

Please login first before commenting.