'ImageFileDescriptor'对象没有属性'objects'

时间:2019-10-17 19:40:56

标签: django django-models django-templates django-views

我正在尝试遍历类别中的图像,但出现'ImageFileDescriptor' object has no attribute 'objects'错误

models.py

class Category(models.Model):
    category_title = models.CharField(max_length=200)
    category_image = models.ImageField(upload_to="category")
    category_description = models.TextField()
    slug = models.SlugField(max_length=200, unique=True, default=1)

    def get_image_path(self, filename):
        gallery_path = os.path.abspath(
            os.path.join(settings.MEDIA_ROOT, self.slug))
        if not os.path.isdir(gallery_path):
            os.mkdir(gallery_path)
        return os.path.join(gallery_path, filename)

    gallery = models.ImageField(upload_to=get_image_path)

    def create_directory(self):
        gallery_path = os.path.abspath(
            os.path.join(settings.MEDIA_ROOT, self.slug))
        if not os.path.isdir(gallery_path):
            os.mkdir(gallery_path)

    def save(self, *args, **kwargs):
        if not self.pk:
            self.create_directory()
        super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        shutil.rmtree(os.path.join(settings.MEDIA_ROOT, self.slug))
        # os.rmdir(os.path.join(settings.MEDIA_ROOT, self.slug))
        super().delete(*args, **kwargs)

    class Meta:
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.category_title

views.py

def category_detail_view(request, slug):
    category = get_object_or_404(Category, slug=slug)
    context = {
        "gallery": Category.gallery.objects.all(),
    }
    return render(request, 'main/category_detail.html', context)

category_detail.html

{% for image in gallery %}
  <div class="col-md-4">
      <a href="{{ image.url }}"> <img src="{{ image.url }}" class="img-responsive img-thumbnail" width="304" height="236"/>
      </a>
   </div>
{% endfor %}

由于某种原因,在Django中创建画廊对我来说很困难。似乎没有大多数人这样做的标准方法。即使我可以使用它,也看不到如何通过管理面板管理上传的图片。前上传删除删除安排等

如果您能为我提供一些启示,那将很棒

0 个答案:

没有答案