Login

User or Group entry field & widget

Author:
Scanner
Posted:
May 6, 2007
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

This is a helper field & widget that lets you ask for a 'user or group'. It presents a select box for whether you wish to enter a user or a group, and then a text field for the name of the user or group you wish to have.

It will validate that the username or group name selected exists.

You would use this like any other field: class AddForumCollectionCreatePermForm(forms.Form): user_or_group = UserOrGroupField(label = "User or Group", help_text = "The user or group to grant " "forum collection create priveleges to.")

 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
from django import newforms as forms
from django.newforms import widgets
from django.newforms import fields
from django.contrib.auth.models import User,Group

############################################################################
#
class UserOrGroupWidget(widgets.MultiWidget):
    """
    A multiwidget composed of a user/group selector, and a text field
    for entering the name of a user or group.
    """

    #######################################################################
    #
    def __init__(self, attrs=None):
        mywidgets = (
            widgets.Select(choices=(('user', 'User'),('group', 'Group'))),
            widgets.TextInput()
            )
        super(UserOrGroupWidget, self).__init__(mywidgets, attrs)

    #######################################################################
    #
    def decompress(self, value):
        if value:
            return value.split(",")
        return ['', '']
    
############################################################################
#
class UserOrGroupField(fields.MultiValueField):
    """
    A field that contains a choice of 'user' or 'group' and a field that
    is the name of a user or group (depending on the multiple choice field.)
    """
    #######################################################################
    #
    def __init__(self, required=True, widget=UserOrGroupWidget(),
                 label=None, initial=None, help_text=None):
        myfields = (
            fields.ChoiceField(choices=(('user', 'User'), ('group', 'Group'))),
            fields.CharField(max_length=30)
            )
        super(UserOrGroupField, self).__init__(myfields, required, widget,
                                               label, initial, help_text)

    #######################################################################
    #
    def compress(self, data_list):
        if data_list:
            return '%s,%s' % (data_list[0],data_list[1])
        return None

    #######################################################################
    #
    def clean(self, value):
        """
        I know that in general a multivaluefield will not need a clean
        method. However the UserOrGroupField needs to make sure that
        the name supplied matches an existing user or group (depending
        on the value of the choice field, ie: 'user' or 'group.'
        """

        # We call the MultiValueField's clean first. We will get back
        # the compressed data so we need to uncompress it first (which
        # we can do inline since we know its form) and then lookup the
        # User or Group in the database to make sure that they exist.
        #
        clean_data = super(UserOrGroupField, self).clean(value)
        user_or_group, name = clean_data.split(',')
        if user_or_group == 'user':
            if User.objects.filter(username = name).count() != 1:
                raise ValidationError('"%s" does not match any username' % \
                                      name)
        else:
            if Group.objects.filter(name = name).count() != 1:
                raise ValidationError('"%s" does not match any group' % name)
        return clean_data

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.