我正在按照本教程在我的Django项目中创建一个视频上传程序,但遇到了以下错误:
。。src/video/views.py“,第9行,showvideo Videofile=LastVideo.Videofile AttributeError:”NoneType“对象没有属性”videofile“
我肯定我错过了一些显而易见的东西,现在已经在寻找答案有一阵子了。 如果有任何帮助,我将不胜感激。
views.py
from django.shortcuts import render
from .models import VideoUpload
from .forms import VideoForm
def showvideo(request):
lastvideo= VideoUpload.objects.last()
videofile= lastvideo.videofile
form= VideoForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
context= {'videofile': videofile,
'form': form
}
return render(request, 'video.html', context)
forms.py
from django import forms
from .models import VideoUpload
class VideoForm(forms.ModelForm):
class Meta:
model = VideoUpload
fields = ["name", "videofile"]
models.py
from django.db import models
class VideoUpload(models.Model):
name= models.CharField(max_length=500)
videofile= models.FileField(upload_to='videos/', null=True, verbose_name="")
def __str__(self):
return self.name + ": " + str(self.videofile)
from django.conf import settings
from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from video.views import (
showvideo,
)
urlpatterns = [
path('showvideo', showvideo, name='showvideo'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
供参考,我更新了模型的名称为'videoupload'vs教程。
数据库中没有last_video记录。 为了防止在such and实例中出错,可以将行:videofile=lastvideo.videofile
更改为
videofile = lastvideo.videofile if lastvideo else None
这将防止抛出错误。 或者,您可以将整个位放在try/except块中。