Commit 710aac8a authored by Anthony Jacob's avatar Anthony Jacob
Browse files

add automatic wordcount updater in the model

parent 4271b806
Loading
Loading
Loading
Loading
+21 −0
Original line number Diff line number Diff line
# Generated by Django 4.1.3 on 2022-11-15 12:15

import django.core.validators
from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ("blog", "0002_rename_photo_blog_photo"),
    ]

    operations = [
        migrations.AddField(
            model_name="blog",
            name="word_count",
            field=models.IntegerField(
                default=0, validators=[django.core.validators.MinValueValidator(0)]
            ),
        ),
    ]
+13 −3
Original line number Diff line number Diff line
from django.db import models
from django.conf import settings
from django.core.validators import MinValueValidator
from PIL import Image

class Photo(models.Model):
@@ -16,10 +17,9 @@ class Photo(models.Model):
        image.thumbnail(self.IMAGE_MAX_SIZE)
        image.save(self.image.path)

    def save(*args, **kwargs) -> None:
        super().save(**args, **kwargs)
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        self.resize_image()
        return self


class Blog(models.Model):
@@ -28,7 +28,17 @@ class Blog(models.Model):
                              blank=True)
    title = models.CharField(max_length=128)
    content = models.CharField(max_length=5000)
    word_count = models.IntegerField(validators=[MinValueValidator(0)],
                                      default=0)
    author = models.ForeignKey(settings.AUTH_USER_MODEL,
                               on_delete=models.CASCADE)
    date_created = models.DateTimeField(auto_now_add=True)
    starred = models.BooleanField(default=False)

    def _word_count(self):
        words = self.content.split(" ")
        return len(words)

    def save(self, *args, **kwargs):
        self.word_count = self._word_count()
        super().save(*args, **kwargs)
+1 −0
Original line number Diff line number Diff line
@@ -12,6 +12,7 @@
            <p> <img alt="" src="{{ post.photo.image.url }}" /> </p>
            <p class="post-content"> {{ post.content }} </p> 
            <p> article créé par {{ post.author }} le {{ post.date_created }} </p>
            <p> cet article fait {{ post.word_count }} mots </p>
            
            
            {% if user.is_authenticated %}