#Model item names
1 messages ยท Page 1 of 1 (latest)
We definitely need more details...
Is this in the admin? Can you share the model code you are referring to?
Yeah, like any details would be already helpful =P
Sure ๐
It is in the admin panel. The following is my model code:
class ItemsModel(models.Model):
price = models.FloatField()
image = models.ImageField()
link = models.URLField()
My issue is that when items are created, they are named "ItemsModel object (1)". I would like to choose their name
Ah, you want to define __str__(self) method on the model
I don't see what can be used on model for name though
Sorry I am new to this. How can I do that
Well you probably want a name field first? Or how you know how it's named?
name\title\code whatever makes sense for your case
I have tried this:
class ItemsModel(models.Model):
name = models.CharField(max_length=500)
price = models.FloatField()
image = models.ImageField()
link = models.URLField()
However when viewing it in the admin panel, it is still named "ItemsModel object (1)"
Yes, only this is not enough, what you see as textual reprentation of an instance is defined by it's __str__() method
e.g.
class ItemsModel(models.Model):
name = models.CharField(max_length=500)
price = models.FloatField()
image = models.ImageField()
link = models.URLField()
def __str__(self):
return f"item {self.name}"
or just self.name or any other string
self.name is most reasonable start probably
Oh, now I get it. Thank you so much
In admin though you can also set display fields that are used
How can I do that?
check official docs on admin, there is a number of useful options
Will do. Thanks again, you helped a ton
Do you know if it will work with image
Just this won't I believe, at least earlier it didn't - it will only display a relative path to file
But you can make a method that returns safe (unescaped) html and call it
then it will display images in admin
Great, thanks ๐
class AbstractSliderImage(FileProcessingMixin, models.Model):
class Meta:
abstract = True
img_alt = models.CharField(max_length=256, default="img")
img = models.ImageField(upload_to='public/')
preview = models.ImageField(default='', upload_to='public/', blank=True)
update_dt = models.DateTimeField(auto_now=True)
is_public = models.BooleanField(default=True)
crc32 = models.CharField(max_length=8, default='', blank=True)
preview_size = (128, 80)
def __str__(self):
return self.img.name
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
if self.img:
self.preview = str(make_preview(self.img.path, unlink=True, size=self.preview_size))
super().save(update_fields=('preview', ), postprocess_files=False)
def preview_html(self):
if self.img and self.preview:
return format_html(
"<a href='{0}'><img src='{1}' alt='{2}' style='width:{3};height:{4}'></a>",
self.img.url, self.preview.url, self.img_alt, self.preview_size[0], self.preview_size[1]
)
else:
return "no image"