valueerror at/new_post/“image”属性没有与之关联的文件

oyjwcjzk  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(301)

在我的django博客站点中,如果我想添加一篇新文章,可以选择是否添加图片。如果我使用图像制作帖子,那么效果很好,但是如果我在没有任何图像的情况下制作帖子,则会显示此错误:
valueerror位于/new_post/“image”属性没有与之关联的文件。
我的代码如下
models.py:

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=300)
    content = models.TextField()
    image = models.ImageField(upload_to='post_image', blank=True)
    date_posted = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return f'{self.author}\'s Post'

    def save(self, *args,**kwargs):
        super().save(*args,**kwargs)
        img = Image.open(self.image.path)
        if img.width > 300 or img.height > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

    def get_absolute_url(self):
        return reverse('post_detail', kwargs={'pk': self.pk})

views.py:

class PostCreateView(CreateView):
    model = Post
    fields = ['title', 'content', 'image']
    success_url = '/'

    def get_context_data(self,**kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'New Post'
        return context

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

home.html:

{% if post.image %}
    <img class="card-img-right flex-auto d-none d-md-block" style="width:200px;height:200px;" src="{{ post.image.url }}" alt="{{ post.title }}">
{% endif %}
xpszyzbs

xpszyzbs1#

我得到了答案。只需在save()方法中添加一个条件
models.py

def save(self, *args,**kwargs):
        super().save(*args,**kwargs)
        if self.image:  # here
            img = Image.open(self.image.path)
            if img.width > 300 or img.height > 300:
                output_size = (300, 300)
                img.thumbnail(output_size)
                img.save(self.image.path)

相关问题