【发布时间】:2019-12-24 14:39:38
【问题描述】:
这是我的模型帖子,我想为特定帖子上传多张图片,所以我创建了从 PostPicture 到 Post 的外键。
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
# image = models.FileField(null = True, blank=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
#code for Thumbnail
# image = models.ImageField(upload_to = "media", default='DEFAULT VALUE')
image_thumbnail = ProcessedImageField(upload_to = "thumbnail",
processors = [ResizeToFill(100,50)],format = 'JPEG',options = {'quality':60},default='DEFAULT VALUE')
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
#code for uploading multiple images
class PostPicture(models.Model):
picture =models.ImageField(upload_to="blog_images", blank=True)
postid =models.ForeignKey(Post,on_delete=models.CASCADE,related_name='pictures')
这是我的模板代码,我在其中迭代图片并尝试显示它们。
{% for i in post.pictures.all %}
<img src = "{{ post.pictures.url }}" height = "200", width="200"/>
{% endfor %}
这是views.py
def post_detail(request, slug):
template_name = 'post_detail.html'
post = get_object_or_404(Post, slug=slug)
comments = post.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request, template_name, {'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form}
)
【问题讨论】:
-
您能分享一下您的 settings.py 文件和 views.py 吗?您必须配置 MEDIA_URL 和 MEDIA_ROOT 才能显示您迭代的图像?
-
STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/')
-
@JimErginbash 我已经用观点编辑了问题
标签: python django django-models django-templates blogs