【问题标题】:I am having a problem in select box, where it can select multiple options, the selected option has a few objects in a sub select box我在选择框中遇到问题,它可以选择多个选项,所选选项在子选择框中有几个对象
【发布时间】:2019-06-06 13:33:58
【问题描述】:

首先,我有一个选择框,我必须在其中选择多个选项。在选择它们时,代码只考虑选择的第一个选项,而忽略其余的其他选项。让我无法保存其他选项。

Views.py

def post(self, request):
    user_site = UserSite.objects.get(user_id = request.POST["user_id"])
    user_site.site_id = request.POST['site']
    user_site.save()
    user_site.user.profile.roles = request.POST['role']
    user_site.user.profile.company_id = request.POST['company']
    user_site.user.profile.save()

Only the option of 'Tamrind Valley' is selected, and 'Green Wood High'' is just ignored

html

<select class="form-control select2 edit-company-select" multiple="multiple" name="company" style="width: 100%;" required >
                        <option></option>
                        {% for company in companies %}
                        <option value="{{ company.id }}"{{company.name}}</option>
                        {% endfor %}
                    </select>

【问题讨论】:

  • 当您有多个选择时,获取它们的正确方法是request.POST.getlist('role')。如果你的关系是m2m,你不能只用profile.roles = ...分配它,你需要使用add()set(),见here
  • 注意:在没有任何验证/清理的情况下将数据库字段分配给发布的值是非常危险的。您不应该使用 request.POST 值,而是像这样将它们保存到数据库中。

标签: python django django-models django-2.0


【解决方案1】:

您可以使用 post get list 存储多项选择 例如:

for i in request.POST.getlist('company'):
    company = Company.objects.create(name = i)

【讨论】:

    猜你喜欢
    • 2018-04-01
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多