Django - 在包含表单列表的视图的 post 方法中获取已发布表单的 id

kka*_*bat 0 html python django

我有一个显示讲座对象列表的视图,每个讲座都有一个文件选择按钮,可以自动提交选定的文件。

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 %}
Run Code Online (Sandbox Code Playgroud)

视图类:

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')
Run Code Online (Sandbox Code Playgroud)

问题是 request.POST['id'] 不返回表单的 id,而是查找任何不存在的名称为 'id' 的元素。

如何根据提交的表格获取lecture.pk值?

Lem*_*eur 5

要获得pk对象的,您可以通过hidden input

<input type='hidden' value='{{lecture.pk}}' name='pk'>
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您永远不会获得带有 key 的音频audio,因为您的表单中不存在该名称,您应该在input file

<input type="file" name='audio' onchange="$('#upload_{{lecture.pk}}').submit();" value="Upload Audio..."/>
Run Code Online (Sandbox Code Playgroud)

由于您的表单是发送文件,因此您错过了提供标头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 %}
Run Code Online (Sandbox Code Playgroud)

可供您查看的数据:

pk = request.POST.get('id')
audio = request.FILES.get('audio')
Run Code Online (Sandbox Code Playgroud)