首页 > 解决方案 > 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})

标签: djangoformscheckboxmany-to-manypreferences

解决方案


您只是在请求instance期间将 传递给表单POST,这意味着当用户使用GET请求重新访问页面时,表单不会绑定到任何实例,并且不会出现之前的选择。

您只需要在初始化表单时传递实例:

else:
    form = CommunitySelectForm(instance=full_user_profile)
return render(request, 'qa/select_communities.html', {'form' : form})

推荐阅读