You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django服务器中视频无法播放求助(YouTube克隆项目)

问题:Django开发YouTube克隆时视频无法播放及上传问题

我是Django新手,正在开发YouTube克隆项目以深入学习Django。目前遇到服务器中视频无法播放的问题,已尝试许久仍未解决,同时也不清楚如何正确上传视频,恳请帮忙解决。

相关代码及信息

1) 模板(video.html)

<video width="320" height="240" controls>
  <source src="{{ video.path }}" type="video/mp4">
Your browser does not support the video tag.
</video>

2) views.py

class VideoView(View):
    template_name = 'base/video.html'

    def get(self, request, id):
        #fetch video from DB by ID
        video_by_id = Video.objects.get(id=id)
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        video_by_id.path = 'http://localhost:8000/get_video/'+video_by_id.path
        context = {'video':video_by_id}
        
        if request.user.is_authenticated:
            print('user signed in')
            comment_form = CommentForm()
            context['form'] = comment_form

        
        comments = Comment.objects.filter(video__id=id).order_by('-datetime')[:5]
        print(comments)
        context['comments'] = comments
        return render(request, self.template_name, context)

class VideoFileView(View):
    
    def get(self, request, file_name):
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        file = FileWrapper(open(BASE_DIR+'/'+file_name, 'rb'))
        response = HttpResponse(file, content_type='video/mp4')
        response['Content-Disposition'] = 'attachment; filename={}'.format(file_name)
        return response

3) models.py

class Video(models.Model):
    title = models.CharField(max_length=30)
    description = models.TextField(max_length=300)
    path = models.CharField(max_length=100)
    datetime = models.DateTimeField(auto_now=True ,blank=False, null=False)
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE)

4) urls.py

app_name = 'Youtube'
urlpatterns = [
    path('home/', HomeView.as_view(), name='homeview'),
    path('login/', LoginView.as_view(), name='loginview'),
    path('register/', RegisterView.as_view(), name='register'),
    path('new_video/', NewVideo.as_view(), name='newvideo'),
    path('redirect/', Redirect.as_view(), name='redirect'),
    path('video/<int:id>', VideoView.as_view(), name='Videoview'),
    path('comment/', CommentView.as_view(), name='comment'),
    path('get_video/<file_name>', VideoFileView.as_view(), name='getvideo'),
]

额外信息

  • 服务器端显示:请求get_video/video.mp4返回404错误
  • 视频实际存储路径:C:\Users\Admin\Desktop\Youtube Redesign\Config\video.mp4

内容的提问来源于stack exchange,提问作者Salman Naqvi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 07:32:10