Reputation: 771
I am uploading a video file to my webpage, which I can also play. However, the moment I want to show all the video files on different page and play them, I get:
AttributeError at /all_videos
QuerySet object has no attribute 'videofile'
I can't figure out what I am doing wrong. Models.py:models.py
class VideoModel(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)
Views.py:
views.py
class ShowVideosView(View):
def get(self, request):
form = VideoForm()
lastvideo = VideoModel.objects.last()
videofile = lastvideo.videofile
return render(request, 'videos.html', {'videofile': videofile, 'form': form})
def post(self, request):
form = VideoForm(request.POST or None, request.FILES or None)
lastvideo = VideoModel.objects.last()
videofile = lastvideo.videofile
form = VideoForm(request.POST or None, request.FILES or None)
if form.is_valid():
name = form.cleaned_data['name']
videofile = form.cleaned_data['videofile']
new_video = VideoModel(name=name, videofile=videofile)
new_video.save()
context = {'videofile': videofile, 'form': form}
return render(request, 'videos.html', context)
class ListOfVideosView(View):
def get(self, request):
all_videos = VideoModel.objects.all()
videofile = all_videos.videofile
context = {'all_videos': all_videos, 'videofile': videofile}
return render(request, 'all_videos.html', context)
all_videos.html:
all_videos.html
{% for video in all_videos %}
<video width='400' controls>
<source src='{{MEDIA_URL}}{{videofile}}' type='video/mp4'
Your browser does not support the video tag.
</video>
{% endfor %}
Upvotes: 0
Views: 56
Reputation: 1413
Your error is just what it looks like all_videos
isn't an instance of VideoModel
, so you can't just get the same attributes off of it.
class ListOfVideosView(View):
def get(self, request):
all_videos = VideoModel.objects.all()
videofile = all_videos.videofile # This is the line where your error is getting raised.
context = {'all_videos': all_videos, 'videofile': videofile}
return render(request, 'all_videos.html', context)
What it looks like you're trying to do is access the videofile
attribute of each VideoModel
in the queryset. If that's correct changing your video list view and HTML to look something like this might help.
views.py
class ListOfVideosView(View):
def get(self, request):
all_videos = VideoModel.objects.all()
context = {'all_videos': all_videos}
return render(request, 'all_videos.html', context)
all_videos.html
{% for video in all_videos %}
<video width='400' controls>
<source src='{{ MEDIA_URL }}{{ video.videofile }}' type='video/mp4'>
Your browser does not support the video tag.
</video>
{% endfor %}
Upvotes: 1