开发者

Django multipleselect selected data

开发者 https://www.devze.com 2023-04-01 01:17 出处:网络
I\'ve been trying to crack this nut for a while but I cannot seem to be able to set selected values for multipleselect. What I have is:

I've been trying to crack this nut for a while but I cannot seem to be able to set selected values for multipleselect. What I have is:

class GroupUsersForm(forms.Form):
    users = forms.MultipleChoiceField()

    def __init__(self, *args, **kwargs):
        super(GroupUsersForm, self).__init__(*args, **kwargs)
        if kwargs.has_key('initial'):
            self.selected = kwargs['initial']['users']
            self.choices = kwargs['initial']['all']
        self.fields[self.get_field_name()] = self.get_users_field()

    def get_users_field(self):
        field_class = forms.MultipleChoiceField
        field = field_class(
            label=_(u"users"),
            choices = self.get_field_choices(),
            widget = FilteredSelectMultiple(_(u"users"), is_stacked= False),
            #initial = self.get_field_initial(),
            required= False
        )
        return field

    def get_field_name(self):
        return 'users'

    def get_field_choices(self):
        choices = [(p.id, p.username) for p in self.choices]       
        return choices

    def get_field_initial(self):
        selected = [(p.id, p.username) for p in self.selected]
        return selected

and i initiate it like that:

uform = GroupUsersForm(initial = {'all': users, 'users':u, 'group':g,})

both users and u are querysets (

users = get_users_with_perms(a).order_by('username', 'last_name', 'first_name')

u = User.objects.filter(Q(groups = g)).order_by('username', 'last_name', 'first_name'))

which in one test case were even the same. No selected options showed up.

I tried setting the initial values myself manually to list based of object ids, passin开发者_运维百科g single id, passing (id, username) tuple and so on... tried using different widget, but all widgets display all the options but none of them are selected.

what am i doing wrong?

Alan


Try setting the choices property of the users field. The value of 'users' in the initial dict should be a list of whatever the keys are for the user choices. For example, if

self.fields['users'].choices = (
                               ('username1','Firstname Lastname'),
                               ('username2','Firstname Lastname'),
                               ('username3','Firstname Lastname'),
                               )

Initial should be ['username1', 'username3']

Then change your form instantiation and __init__ to the following:

uform = GroupUsersForm(users, initial = {'users':u,})

def __init__(self, user_choices, *args, **kwargs):
    super(GroupUsersForm, self).__init__(*args, **kwargs)
    self.fields['users'].choices = user_choices
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号