在服务器上无法加载视频的缩略图| Django



我对Django相当陌生,目前我正在制作一个Youtube克隆来深入了解Django。所以我现在面临的问题是,当我运行服务器时,我似乎不能让缩略图出现在主页上。我花了很多时间尝试,但似乎找不到答案!我将提供我认为与我的问题有关的东西;

<<p>

1)模板/strong>homeview.html:

`{% block body %}
{% for video in most_recent_video %}
<div class="video-card">
<img src="/get_thumbnail/{{ video.thumbnail.path }}" alt="{{ video.title }} thumbnail">
<h5>{{ video.title }}</h5>
<p>Uploaded By {{ video.user }} on {{ video.datetime }}</p>
<p>{{ video.description }}</p>
<p><a href="/video/{{ video.id }}">Watch Video</a></p>
</div>
{% endfor %}
{% endblock %}`

thumbnail.html:

`{% block body %}
<div class="header-bar">
<h2>Thumbnail View</h2>
<hr>
</div>
<div class="main-body">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<table>
{{ form.as_p }}
</table>
<button type="submit">Upload Thumbnail</button>
</form>

{% if errors %}
<div class="errors">
<h3>Errors:</h3>
<ul>
{% for field_errors in errors.values %}
{% for error in field_errors %}
<li>{{ error }}</li>
{% endfor %}
{% endfor %}
</ul>
</div>
{% endif %}
</div>
{% endblock %}`

2) views.py

`class ThumbnailView(View):
template_name = 'base/thumbnail.html'
def get(self, request):
if not request.user.is_authenticated:
return HttpResponseRedirect('/login/')
form = ThumbNailForm()
return render(request, self.template_name, {'form': form})
def post(self, request):
form = ThumbNailForm(request.POST, request.FILES)
if form.is_valid():
# Create a new Thumbnail entry
title = form.cleaned_data['title']
thumbnail_file = form.cleaned_data['file']
# Generate a random filename for the thumbnail
random_chars = ''.join(random.choices(
string.ascii_uppercase + string.digits, k=10))
filename = random_chars + thumbnail_file.name
# Save the thumbnail file
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
thumbnail_path = os.path.join(BASE_DIR, filename)
with open(thumbnail_path, 'wb') as f:
f.write(thumbnail_file.read())
thumbnail = Thumbnail(title=title, path=filename)
thumbnail.save()
return HttpResponseRedirect('/home/')
else:
return render(request, self.template_name, {'form': form, 'errors': form.errors})
class ThumbnailFileView(View):
def get(self, request, file_name):
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
stripped_file_name = file_name[10:] 
file = FileWrapper(open(os.path.join(BASE_DIR, stripped_file_name), 'rb'))
response = HttpResponse(file, content_type='image/jpg')
response['Content-Disposition'] = 'attachment; filename={}'.format(stripped_file_name)
return response`

3) urls . py

`path('get_thumbnail/<file_name>', ThumbnailFileView.as_view(), name='getthumbnail'),
path('thumbnail/', ThumbnailView.as_view(), name='thumbnail'),`

4) 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)
likes = models.IntegerField(default=0)
dislikes = models.IntegerField(default=0)
class Thumbnail(models.Model):
title = models.CharField(max_length=50)
path = models.CharField(max_length=100)
class ThumbnailView(models.Model):
image = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='thumbnails')`

5) forms.py

`class ThumbNailForm(forms.Form):
title = forms.CharField(label='Title', max_length=50)
file = forms.FileField()`

这是我运行server时的样子

6)控制台错误

`<QuerySet [<Video: Video object (43)>, <Video: Video object (42)>, <Video: Video object (41)>, <Video: Video object (40)>, <Video: Video object (39)>, <Video: Video object (38)>, <Video: Video object (37)>, <Video: Video object (36)>, <Video: Video object (35)>]>
[01/Apr/2023 15:44:21] "GET /home/ HTTP/1.1" 200 16180
Not Found: /get_thumbnail/
[01/Apr/2023 15:44:21] "GET /get_thumbnail/ HTTP/1.1" 404 13168`

7)图像路径

`
C:UsersAdminDesktopYoutube RedesignConfigimg1.jpg
C:UsersAdminDesktopYoutube RedesignConfigimg2.jpg
C:UsersAdminDesktopYoutube RedesignConfigimg3.jpg`

我一直在尝试各种各样的事情,但似乎不能使它工作!!

您可以在views.py中编辑Video模型。您应该将thumbnail添加到Video模型中,以便在homeview.html中引用它。注意,其他模型字段在homeview.html

中工作得很好
import PIL
class Video(models.Model):
title = models.CharField(max_length=30)
description = models.TextField(max_length=300)
path = models.CharField(max_length=100)
thumbnail = models.ImageField(upload_to='images/')
datetime = models.DateTimeField(auto_now=True ,blank=False, null=False)
user = models.ForeignKey('auth.User', on_delete=models.CASCADE)
likes = models.IntegerField(default=0)
dislikes = models.IntegerField(default=0)

当您将thumbnail添加到Video模型时,您将图像标记中的src值替换为{{ video.thumbnail.url }}

你的homeview.html应该是这样的。

{% block body %}
{% for video in most_recent_video %}
<div class="video-card">
<img src="{{ video.thumbnail.url }}" alt="{{ video.title }} thumbnail">
<h5>{{ video.title }}</h5>
<p>Uploaded By {{ video.user }} on {{ video.datetime }}</p>
<p>{{ video.description }}</p>
<p><a href="/video/{{ video.id }}">Watch Video</a></p>
</div>
{% endfor %}
{% endblock %}

相关内容

  • 没有找到相关文章

最新更新