Django从DropDownlist传递到View

时间:2016-09-06 09:13:00

标签: python django django-forms django-views

我正在尝试获取所选下拉菜单的值。我做了以下操作,它返回了一个' null'值。

我认为问题在于:newupload = request.POST(' nameProjects')但我不确定如何使其正常工作。

upload.html

<form class="form" method="POST" action="upload">
<select id="ddProjects" name="nameProjects">
    {% for project in projects %}
      <option value="{{ project.id }}">{{ project.name }}</option>
    {% endfor %}
</select>
</form>

views.py

def upload_new(request):
    newupload = Upload()
    projects = Project.objects.all()
    newupload.project = request.POST['nameProjects']
    newupload.save()
return render(request, 'upload.html', {'projects':projects})    

1 个答案:

答案 0 :(得分:0)

在views.py中,您应该使用request.POST [&#39; nameProjects&#39;]因为request.POST会提供字典。如果要将项目对象存储在上传模型中,我们需要提供项目模型实例变量或者可以给出id。

def upload_new(request):

    newupload = Upload()

    projects = Project.objects.all()

    newupload.project_id = request.POST['nameProjects']

    newupload.save()

return render(request, 'upload.html', {'projects':projects})