Django 中的多选表单字段
我正在应用程序引擎路径上开发应用程序。 我想制作具有多项选择的表单(用户可以接受的语言)。 代码如下所示:
语言设置:
settings.LANGUAGES = ((u"cs", u"Čeština"), (u"en", u"English"))
表单模型:
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)
表单渲染正常(所有语言都有复选框。ID、NAME 都可以。) 但是,如果我为用户保存某些语言,这些语言不会选中复选框。
用户模型如下
class User(User):
#...
languages = db.StringListProperty()
#...
所示:
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'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:
settings.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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我是这样解决的:
I solved it this way: