'Error when autocreating slug in django models
This is my model:
class post (models.Model):
title = models.CharField(max_length=200)
post = models.CharField(max_length=75000)
picture = models.URLField(max_length=200, default="https://i.ibb.co/0MZ5mFt/download.jpg")
show_date = models.DateTimeField()
slug = models.SlugField(editable=False)
def save(self, *args, **kwargs):
to_slug = f"{self.title} {self.show_date}"
self.slug = slugify(to_slug)
super(Job, self).save(*args, **kwargs)
When I run my website and try to add an item from the admin portal, though, I get this:
NameError at /admin/blog/post/add/
name 'Job' is not defined
I got the autoslugging part from here, what is 'Job' that I have to define?
Solution 1:[1]
Your class is post, not Job, so your super(…) call should be super(post, self), but as of python-3.x, you do not need to specify the name, so you can work with:
class Post(models.Model):
title = models.CharField(max_length=200)
post = models.CharField(max_length=75000)
picture = models.URLField(max_length=200, default='https://i.ibb.co/0MZ5mFt/download.jpg')
show_date = models.DateTimeField()
slug = models.SlugField(editable=False)
def save(self, *args, **kwargs):
to_slug = f"{self.title} {self.show_date}"
self.slug = slugify(to_slug)
super().save(*args, **kwargs)
Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from
topostPost.
Note: You can make use of
django-autoslug[GitHub] to automatically create a slug based on other field(s).
Note: Normally you should not change slugs when the related fields change. As is written in the article Cool URIs don't change [w3.org], URIs are not supposed to change, since these can be bookmarked. Therefore the slug should only be created when creating the object, not when you change any field on which the slug depends.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Willem Van Onsem |
