django - Django 坚持 ModelMultipleChoiceField 选择
问题描述
我有一个 ModelMultipleChoiceField,它允许用户选择一组我的“社区”模型中的一个或多个(类似于用户加入 subreddit)。当用户重新打开页面以选择社区时,用户之前选择的字段上没有复选框。我想让以前选择的社区保留复选框,因此当用户点击提交时,如果他们不重新选择以前的选择,他们以前的选择就不会被忘记。
这是我的表格:
class CustomChoiceField(forms.ModelMultipleChoiceField):
def label_from_instance(self, obj):
return obj.name
class CommunitySelectForm(forms.ModelForm):
community_preferences = CustomChoiceField(queryset=Community.objects.all(), widget=forms.CheckboxSelectMultiple)
class Meta:
model= UserQAProfile
fields = ['community_preferences']
这是我的模板:
<div class="col-sm-8 input">
<form method="post" enctype='multipart/form-data'>
{% csrf_token %}
{{ form.as_p }}
<input class="btn btn-submit pull-left" type="submit" value="Choose Communities" />
</form>
</div>
UserQAProfile 模型有一个 ManyToMany 字段来存储首选项:
community_preferences = models.ManyToManyField(Community)
这是初始化表单的视图:
def joinCommunities(request, user_id):
user_ob = get_user_model().objects.filter(id=user_id).first()
full_user_profile = UserQAProfile.objects.filter(user=user_ob).first()
if request.method == 'POST':
form = CommunitySelectForm(request.POST, instance=full_user_profile)
if form.is_valid():
form.save()
context = {'user': full_user_profile, 'full_user_profile':full_user_profile}
context['communities'] = context['user'].community_preferences.all()
return render(request, 'qa/profile.html', context)
else:
form = CommunitySelectForm()
return render(request, 'qa/select_communities.html', {'form' : form})
解决方案
您只是在请求instance
期间将 传递给表单POST
,这意味着当用户使用GET
请求重新访问页面时,表单不会绑定到任何实例,并且不会出现之前的选择。
您只需要在初始化表单时传递实例:
else:
form = CommunitySelectForm(instance=full_user_profile)
return render(request, 'qa/select_communities.html', {'form' : form})
推荐阅读
- android - 我可以在弹出的 react-native 项目中安全地删除 app.json 吗?
- python - 哪些功能或模块需要连续输入?
- c# - .Net 5 动作过滤器在使用 AspNetCore.CacheOutput 时不起作用
- javascript - 在 splidejs 轮播中显示用户单击时出现主滑块的问题
- reactjs - 如何在 asyncapi-react-component 中启用规范扩展?
- dynamic - 资源内部的 Terraform 条件内容块
- c# - SharpSerializer:从反序列化中忽略属性/属性
- java - 虚拟路径/文件夹
- javascript - 在两个表格中画香草 JS
- java - 混淆 JAR 文件后的 VerifyError