Answers for "django slugify on create"

1

slugify django

from django.template.defaultfilters import slugify

# in the view maybe while saving the form...
def savedata()
    form = someform(request.POST or None)
  	if form.is_valid():
        new_post = form.save(commit=False) #for holding it before actually saving
        # slugify returns elephant-is-big if passed slugify("elephant is big")
        # and therefore a hyphened slug
        new_post.slug = slugify(form.title) 
        new_post.save()

# model may look like this
class SomeModel(models.Model):
    title = models.Charfield()
    slug = models.SlugField(unique=True)
    ## other fields
Posted by: Guest on July-19-2021

Python Answers by Framework

Browse Popular Code Answers by Language