1

I would like to replace all the spaces in my defined url objects from my Article model to "-". However, my code below doesn't seem to work.

def index(request):
    change_urls = Article.objects.all()
    for i in change_urls:
        i.url.replace(" ", "-")
        i.save()

1 Answers1

1

.replace(..) creates a new string, it does not modify the string. You can thus work with:

def index(request):
    change_urls = list(Article.objects.all())
    for i in change_urls:
        i.url = i.url.replace(' ', '-')
    Article.objects.bulk_update(change_urls, fields=('url',))
    # …

But if you want to "slugify", please use the slugify(…) function [Django-doc].

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555