首页 > 解决方案 > 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 值?

标签: pythonhtmldjango

解决方案


要拥有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')

推荐阅读