python - Django - 在包含表单列表的视图的 post 方法中获取已发布表单的 id
问题描述
我有一个显示 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 值?
解决方案
要拥有pk
对象,您可以通过hidden input
<input type='hidden' value='{{lecture.pk}}' name='pk'>
顺便说一句,您永远不会使用 key 获得音频audio
,因为该名称在您的表单中不存在,您应该在input file
<input type="file" name='audio' onchange="$('#upload_{{lecture.pk}}').submit();" value="Upload Audio..."/>
由于您的表单是发送文件,因此您错过了为标题提供enctype='multipart/form-data'
,因此您的整个表单将如下所示:
{% for lecture in past_lectures %}
<form method = "post" id=upload_{{lecture.pk}} action="" enctype='multipart/form-data'>
{% csrf_token %}
<input type='hidden' value='{{lecture.pk}}' name='id'>
<input type="file" name='audio' onchange="$('#upload_{{lecture.pk}}').submit();" value="Upload Audio..."/>
</form>
{% endfor %}
可供您查看的数据:
pk = request.POST.get('id')
audio = request.FILES.get('audio')
推荐阅读
- go - 如何使用 REST API 从 go-kit 微服务向外部服务发出 HTTP 请求
- excel - 查找表边界的最佳 VBA 方法
- bash - 不能用不同的值设置不同的json值
- sql - 查询性能更好
- android - 如何在uri权限中获取字符串的第一部分(android)
- swift - 无法使用 SQLite.swift 创建 sqlite 文件“无法在行中打开文件...”
- java - Java 链式映射方法和使用可选
- javascript - Backspace 在 Vue JS (REGEX) 的输入字段中不起作用
- excel - 在 azure 函数中使用 open xml 2.14.0 更新单元格时不应用公式
- amazon-web-services - 在 RN/Expo 应用程序中隐藏 API 密钥的方法有哪些?