this_is_a_person
this_is_a_person

Reputation: 9

Why do I get "'Image' object has no attribute 'name'" error when I visit Images database in admin panel, using Django?

I try to implement a ForeignKey in my models and I get an error when I save multiply images to the Image model.

In two words the error started to appear when I wrote this line in Views.py: post = instance, I also tried to make it post = instance.id, but I got another error. The post fileld is models.ForeignKey('Post', on_delete=models.CASCADE). As I have understood, when you use ForeignKey you can't put an integer to an object in the field of it's id. This is why I have put a whole instance. What do I do wrong? Thank you in advance.

This is my code:

Views.py:

def adminpanel(request):
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES)
        instance = form.save(commit=False)
        if form.is_valid():
            form.save()

        images = request.FILES.getlist('image')
        for image in images: 
            picture = Image.objects.create(
                post = instance,
                image = image,
            )  

Models.py:

from django.db import models
from imagekit.models import ImageSpecField
#from PIL import Image
import PIL.Image
# Create your models here.

class Post(models.Model):
    name = models.CharField(max_length = 100)
    thumbnail = models.ImageField(upload_to ='uploads/posts/')
    thumbnail_small = ImageSpecField(source='thumbnail',
                                      format='JPEG',
                                      options={'quality': 50})
    category = models.CharField(max_length = 100, default = 'initial')
    slug = models.SlugField(default = 'initial',unique = True)
    body = models.TextField(default = 'initial')
    created_at = models.DateTimeField(auto_now_add=True)

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

    class Meta:
        ordering = ('-created_at',)
 

    def __str__(self):
        return self.name

class Image(models.Model):
    post = models.ForeignKey('Post', on_delete=models.CASCADE)
    image = models.ImageField(upload_to ='uploads/posts/')
    def __str__(self):
        return self.name

Upvotes: 0

Views: 920

Answers (1)

Yeamin Mahmud
Yeamin Mahmud

Reputation: 67

Your Image model does not have name attribute. If you want to use "name" from Post you can return self.post.name

class Image(models.Model):
    post = models.ForeignKey('Post', on_delete=models.CASCADE)
    image = models.ImageField(upload_to ='uploads/posts/')

    def __str__(self):
        return self.post.name

Upvotes: 2

Related Questions