pythonpython-3.xdjangodjango-modelsslugify

name 'slugify' is not defined


Once a user had logged into my site he could write a post and update it.

Then I was making progress in adding functionality which allowed people to make comments. I was at the stage where I could add comments from the back end and they would be accurately displayed on the front end.

Now when I try and update posts I get an error message.

enter image description here

I assume it is because there is a foreign key linking the comments class to the post class. I tried Googling the problem and looking on StackOverflow but I wasn't entirely convinced the material I was reading was remotely related to my problem. I am struggling to fix the issue because I barely even understand / know what the issue is.

    # Create your models here.
class Post(models.Model):
    title = models.CharField(max_length=100)
    content =  models.TextField()
    date_posted = models.DateTimeField(default=timezone.now())
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    url= models.SlugField(max_length=500, unique=True, blank=True)

def save(self, *args, **kwargs):
    self.url= slugify(self.title)
    super().save(*args, **kwargs)

def __str__(self):
    return self.title 

def get_absolute_url(self):
    return reverse('article_detail', kwargs={'slug': self.slug})


class Comment(models.Model):
    post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)

class Meta:
    ordering = ['created_on']

def __str__(self):
    return 'Comment {} by {}'.format(self.body, self.name)

Solution

  • You need to import the slugify(..) function [Django-doc]:

    from django.db import models
    from django.utils.text import slugify
    
    class Post(models.Model):
        title = models.CharField(max_length=100)
        content =  models.TextField()
        date_posted = models.DateTimeField(default=timezone.now())
        author = models.ForeignKey(User, on_delete=models.CASCADE)
        url= models.SlugField(max_length=500, unique=True, blank=True)
    
        def save(self, *args, **kwargs):
            self.url= slugify(self.title)
            super().save(*args, **kwargs)
    
    # …