Прикрепленные изображения не отображаются в подробном представлении моего блога на сайте. С другой стороны, они отображаются только тогда, когда я добавляю их через страницу администратора. У меня есть старые посты, подробные представления которых могут отображаться, но с тех пор, как эта проблема началась, подробный вид больше не открывается.
Отображается следующая ошибка:
The 'blog_Main_Img' attribute has no file associated with it
МОИ МОДЕЛИ
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
# a class for text to be posted
class Post(models.Model):
title = models.CharField(max_length=50)
content = models.TextField(blank=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, related_name='blog_author',on_delete=models.CASCADE)
blog_Main_Img = models.ImageField(upload_to='images/', verbose_name='Image',blank=True,default='')
# this allow the method to be called as a string
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog-home')
@property
def image_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('blog-home')
МОИ ПРОСМОТРЫ
from django.shortcuts import render,get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
from .models import Post
def home(request):
context ={
'posts': Post.objects.all()
}
return render(request, 'blog/home.html', context)
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = '-date_posted'
paginate_by = 5
class UserPostListView(ListView):
model = Post
template_name = 'blog/user_posts.html'
context_object_name = 'posts'
paginate_by = 5
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Post.objects.filter(author=user).order_by('-date_posted')
class PostDetailView(DetailView):
model = Post
context_object_name = "post"
class PostCreateView(LoginRequiredMixin,CreateView):
model = Post
fields = ['title', 'content', 'blog_Main_Img']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
fields = ['title', 'content', 'blog_Main_Img']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Post
success_url = '/'
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
def about(request):
return render(request, 'blog/about.html', {'title': 'about'})
МОЙ ШАБЛОН (post_detail. html)
{% extends "blog/base.html" %}
{% block content %}
<br><br><br>
<style>
body {
background-image: url('/static/img/workplace-1245776_1280.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
</style>
<article class="media content-section">
<img class="rounded-circle article-img" src="{{object.author.profile.image.url}}" >
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ object.author }}</a>
<small class="text-muted">{{ post.date_posted }}</small>
{% if object.author == user %}
<div>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a>
</div>
{% endif %}
</div>
<h2 class="article-title">{{ object.title }}</h2>
<p class="article-content">{{ object.content }}</p>
<!-- this shows an image in the detail view. when i add 's' to post, it displays the image -->
<!--the image can only be shown when i add from the admin-->
<img src="{{ post.blog_Main_Img.url|default_if_none:'#' }}" alt="" width="40%" height="100%">
<!-- this shows an image in the detail view. when i add 's' to post, it displays the image -->
</article>
<br><br><br>
{% endblock content %}
МОИ URL
from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView
)
from . import views
urlpatterns = [
path('',PostListView.as_view(), name = 'blog-home' ),
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
path('post/<int:pk>/',PostDetailView.as_view(), name = 'post-detail' ),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update',PostUpdateView.as_view(), name = 'post-update' ),
path('post/<int:pk>/delete',PostDeleteView.as_view(), name = 'post-delete' ),
# path('showvideo/', views.showvideo,name = 'showvideo'),
path('about/',views.about, name = 'blog-about' ),
]
FORMS.PY
from django import forms
from . models import Post
class ImageForm(forms.ModelForm):
class Meta:
model = Post
fields = ['name', 'blog_Main_Img']
APPS.PY
from django.apps import AppConfig
class BlogConfig(AppConfig):
name = 'blog'
ADMIN.PY
from django.contrib import admin
from .models import Post
admin.site.register(Post)