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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 4 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.