0

I've created this simple counter with Python3.6 and I would like to do the same thing with a TextField in my models.

What interests me is the line 37 that is here; I want to transport it in Django.

class Post(models.Model):
    title = models.CharField(max_length=70, help_text="Write post title here. The title must be have max 70 characters", verbose_name="Titolo", unique=True)
    slug = models.SlugField(verbose_name="Slug", unique="True", help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents")
    tagline = models.TextField(max_length=200, help_text="Write a post short description here. The description must be have max 200 characters", verbose_name="Breve descrizione dell'articolo")
    contents = models.TextField(help_text="Write your post here", verbose_name="Contenuti")
    time_of_reading = models.IntegerField(count(contents) / 250)
    highlighted = models.BooleanField(default=False, help_text="If you want that the post went be highlighted, click on this area", verbose_name="Articolo in evidenza")

    def __str__(self):
        return self.title

With this I've this error:

  File "/var/www/html/dev/miosito/django/v2.1/versions/aproject/muletto/models.py", line 4, in <module>
    class Post(models.Model):
  File "/var/www/html/dev/miosito/django/v2.1/versions/aproject/muletto/models.py", line 10, in Post
    time_of_reading = models.IntegerField(count(contents) / 250)

NameError: name 'count' is not defined

I'm newbie into the development world

MaxDragonheart
  • 1,117
  • 13
  • 34
  • 1
    Where did you get this from? Does models.TextField have a count function? I suggest if you are a newbie you should stick to basic concepts. That said this is the bigger issue imo... Why are you wasting a space on a field that can be easily calculated at any time? I suggest you read about database normalization and why storing such fields is not a good idea. – diek Oct 16 '18 at 23:46
  • Thanks for the suggestion. I think it's possible do the same thing with a javascript. – MaxDragonheart Oct 17 '18 at 06:14

1 Answers1

1

One possibility is override method save(). In save() do something like that:

    self.thistime_of_reading = self.count(self.contents)

Here: Django. Override save for model

Mtzw
  • 48
  • 8
  • I must add a stuff like this in the model Post? ` def save(self): self.thistime_of_reading = count(self.contents)/250 ` If yes I've this error: ` File "/var/www/html/dev/miosito/django/v2.1/versions/aproject/muletto/models.py", line 4, in class Post(models.Model): File "/var/www/html/dev/miosito/django/v2.1/versions/aproject/muletto/models.py", line 9, in Post time_of_reading = models.IntegerField(count(contents) / 250) NameError: name 'count' is not defined` – MaxDragonheart Oct 16 '18 at 08:28
  • You have to define, maybe in model, function count, and call it in save method. – Mtzw Oct 16 '18 at 09:24