V
V
Vova1357982021-06-07 20:55:07
Django
Vova135798, 2021-06-07 20:55:07

How to make slug repeat title?

Please tell me how to make it so that when filling in the title field, the slug is filled in by itself

class Book(models.Model):
    title = models.CharField(max_length=155, verbose_name='Название книги')
    summary = models.TextField(blank=True, verbose_name='Краткое описание')
    photo = models.ImageField(upload_to='books/%m/%d', null=True, blank=True)
    genre = models.ForeignKey(Genre, on_delete=models.CASCADE, null=True)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True)
    creation_date = models.DateField(blank=True, verbose_name='Дата создания')
    slag = models.SlugField(unique=True)

    def __str__(self):
        return self.title

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Daler Hojimatov, 2021-06-09
@Vova135798

from django.utils.text import slugify
class Book(models.Model):
    ...
    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Book, self).save(*args, **kwargs)

I still do this in the admin
class BooksAdmin(admin.ModelAdmin):
    ...
    prepopulated_fields = {'slug': ('title',)}
    ...
admin.site.register(Book, BooksAdmin)

The feature in the admin panel immediately automatically changes the slug when entering text in the title field

D
Denis Melnikov, 2021-06-08
@Mi11er

The answer is found quite simply, from third-party libraries to a simple solution while saving

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question