开发者

django ModelMultipleChoiceField (default values)

I've been searching and trying to get this to work for the past few hours and I can't

I have a list of skills that I take from the database:

forms.ModelMultipleChoiceField(
                              skills.objects.all(), 
                              required=True, 开发者_如何学编程
                              widget=forms.CheckboxSelectMultiple(),
                              label='Check your skills.',
                              initial=skill_list.objects.filter(user='void'),
                              )

but this isn't working as I would expect it to work. I basically want to display the list of skills (all of them) and the ones that the user has checked to be checked ... pff I cant even explain right.

After the user checks the checkbox and hits submit in another page I want to display all skills and the one the user checked to be checked.

Lets say I have a b c and the user checks b and hits submit when in w/e page I want to display a uncheked b checked c unchecked.

PS: If I use skills.objects.all(), I get in the HTML value 1 and a how can I make it like this:

skills = (
         ('a', 'a'),
         ('b', 'b'),
         )  

Instead of ('1', 'a'), ('2', 'b').


Your question(s) are a little unclear, but il still try my best.

Firstly,

I wanna display all skills and the one the user checked to be checked ...

The form doesnot have access to the user, so you need to pass it the user. You could do this by overloading the __init__ method like so:

    def __init__(self, **kwargs):
        current_user = kwargs.pop ('user')
        super(FormName, self).__init__(attrs)

then for setting the initially chosen values,

self.fields['skills'].initial = skill_list.objects.filter(user='void')

Remember you must do this after calling the constructor of the base class.

Finally,

PS: if i use skills.objects.all() I get in the html value 1 and a how can I make this as

skills = ( ('a', 'a'), ('b', 'b'), )

instead of ('1', 'a'), ('2', 'b')

Why would you want to do that? The numbers are the primary keys of the rows from you 'skills' table. Django uses this to setup the appropriate relationships.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜