【问题标题】:The 'file' attribute has no file associated with it'file' 属性没有与之关联的文件
【发布时间】:2022-01-13 15:41:37
【问题描述】:

当我从 addvideo 模板文件添加视频时,它会说:“文件”属性没有与之关联的文件。我希望用户能够上传视频。

当我从我的管理员添加视频时,它工作正常,但是当我从我的表单页面添加它时,它在管理员中添加了视频,但它没有在主页中显示视频并且它突出显示了我的视频标签 src="{ {video.file.url}}”说:“文件”属性没有与之关联的文件。

这是我的模型:

class Video(models.Model):
    file = models.FileField(upload_to='file', null=False, blank=False)

这是我的看法:

def addvideo(request):
    if request.method == 'POST':
        file = request.FILES.get('video')
        videos = Video.objects.create(
            file=file
        )
        return redirect('home')
    return render(request, 'addvideo.html') 

def home(request):
    videos = Video.objects.all()
    return render(request, 'home.html', {'videos': videos})

这是我的 addvideo 模板:

        <div class="col-md-5">
            <form action="" method="POST">
                {% csrf_token %}
            <div class="card">        
                <div class="form-group m-3">
                    <label>Upload Your Video</label><br><br>
                     <input required name="video" type="file" class="form-control-file">
                </div>
                <button type="submit" class="btn btn-primary">Post</button>
            </div>
        </form>
        </div>

这是我的主页模板:

    <div class="container">
        {% for video in videos %}
        <div class="row justify-content-center">
            <video style="height: 500px; width: 500px;" controls src="{{video.file.url}}"> 
            </video>
        </div>
        {% endfor %}
          </div>

【问题讨论】:

  • enctype="multipart/form-data" 添加到&lt;form&gt;
  • 先生,我添加了它,但它不起作用。
  • 您还应该删除Videos 中指向不(不再)存在的文件的记录。或许最好清空整个表,然后重新开始。

标签: django-views django-forms django-templates


【解决方案1】:

为了提交带有 HTML 表单的文件,您需要指定它将如何发送文件内容:您需要指定 enctype="…" [MozillaDev]。你可以这样做:

<form action="" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <div class="card">        
        <div class="form-group m-3">
            <label>Upload Your Video</label><br><br>
            <input required name="video" type="file" class="form-control-file">
        </div>
        <button type="submit" class="btn btn-primary">Post</button>
    </div>
</form>

【讨论】:

    猜你喜欢
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2023-02-21
    • 2021-11-18
    • 2021-02-11
    • 2020-03-08
    相关资源
    最近更新 更多