【问题标题】:Django - get id of posted form in post method of view that contains list of formsDjango - 在包含表单列表的视图的 post 方法中获取已发布表单的 id
【发布时间】: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 的值?

【问题讨论】:

    标签: python html django


    【解决方案1】:

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

    <input type='hidden' value='{{lecture.pk}}' name='pk'>
    

    顺便说一句,您将永远无法获得带有密钥 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')
    

    【讨论】:

    • 我是 Django 新手,所以这非常有帮助!谢谢。
    猜你喜欢
    • 2014-01-24
    • 2016-06-20
    • 1970-01-01
    • 2016-11-20
    • 2016-08-02
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    相关资源
    最近更新 更多