【发布时间】: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