【发布时间】:2018-05-23 21:40:14
【问题描述】:
我有一个显示 Lecture 对象列表的视图,每个讲座都有一个文件选择按钮,可以自动提交所选文件。
html模板中的相关部分:
{% for lecture in past_lectures %}
<form method = "post" id=upload_{{lecture.pk}} action="">
{% csrf_token %}
<input type="file" onchange="$('#upload_{{lecture.pk}}').submit();" value="Upload Audio..."/>
</form>
{% endfor %}
视图类:
class LectureListView(ListView):
model = Lecture
ordering = ('name', )
context_object_name = 'past_lectures'
template_name = 'professor/home.html'
def get_queryset(self):
professor = self.request.user.professor
lecture_queryset = Lecture.objects.filter(course__professor = professor)
return lecture_queryset
def post(self, request,):
pk = int(request.POST['id'].split('_').[-1]) #return the pk portion of the id of the form
lecture = Lecture.objects.get(pk=pk)
lecture.audio = request.FILES['audio'] #audio is the name of the filefield in Lecture model
lecture.save()
return reverse('professor:home')
问题是 request.POST['id'] 不返回表单的 id 而是查找名称为 'id' 但不存在的任何元素。
如何根据提交的表单获取 Lecture.pk 的值?
【问题讨论】: