In Python Crash Course chapter 18 we make a Learning Log website.
I can't make this return just the first 50 characters of a >50 character long entry when I go into the Learning Log website that we make (through localhost:8000). It doesn't show the ellipsis either, it just shows the whole entry.
from django.db import models
from django.contrib.auth.models import User
class Topic(models.Model):
"""A topic the user is learning about"""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
"""Return a string representation of the model."""
return str(self.text)
class Entry(models.Model):
"""Something specific learned about a topic"""
topic = models.ForeignKey(Topic, on_delete=models.PROTECT)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'entries'
def __str__(self):
"""Return a string representation of the model."""
if len(self.text) > 50:
return f"{str(self.text)[:50]}..."
else:
return f"{str(self.text)}"
It is the same whether I include the if len(self.text) > 50
statement or not.
My code differs somewhat from the book in that:
- I use
on_delete=models.PROTECT
, as I understand that CASCADE can cause weird issues like accidentally getting something deleted that you didn't intend to delete - I use
str(self.text)
instead of justself.text
in the__str__
definitions; if I don't it raises a pylint error "Value 'self.text' is unsubscriptable". I can still make entries without thestr()
conversion - it still won't show only the first 50 characters however.
Is it something about how models.TextField()
function that causes this? Am I supposed to have to do the str()
conversions to make the self.text
variable "subscriptable"?