【问题标题】:Django persist ModelMultipleChoiceField selectionsDjango 坚持 ModelMultipleChoiceField 选择
【发布时间】:2018-07-01 01:15:57
【问题描述】:

我有一个 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})

【问题讨论】:

  • 请向我们展示初始化表单的视图代码。
  • @solarissmoke 添加了!

标签: django forms checkbox many-to-many preferences


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-08-02
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 2016-12-29
    • 2011-12-31
    • 2020-10-17
    相关资源
    最近更新 更多