开发者

Multi choice form field in Django

I'am developing application on app-engine-path. I would like to make form with multichoice (acceptably languages for user). Code look like this:

Language settings:

setti开发者_JAVA技巧ngs.LANGUAGES = ((u"cs", u"Čeština"), (u"en", u"English"))

Form model:

class UserForm(forms.ModelForm):
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)

    languages = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                          choices=settings.LANGUAGES)

The form is rendered o.k. (all languages have checkbox. IDs, NAMEs is ok.) But if I save some languages for user, those languages don't check checkboxes.

User model look like this

class User(User):
  #...
  languages = db.StringListProperty()
  #...

and view:

def edit_profile(request):
    user = request.user

    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            # ...
    else:
        form = UserForm(instance=user)        
    data = {"user":user, "form": form}
    return render_to_response(request, 'user_profile/user_profile.html', data)


I solved it this way:

some_view(request):
    ...
    form = UserForm(instance=user, initial={"languages":user.languages})  
    ...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜