Reputation: 137
So my question was how I can generate a random UID or slug for my CMS. If I use the default id which is coming from API v2 people can easily guess my next post URL easily.
Is there any way to add a unique slug/ID/UUID for my wagtail CMS?
Upvotes: 0
Views: 494
Reputation: 1258
A variant on the answer that I use for user ID's:
import random
import string
from django_extensions.db.fields import AutoSlugField
....
class CustomUser(AbstractUser):
....
uuid = AutoSlugField(unique=True)
....
def slugify_function(self, content):
return ''.join((random.choice(string.ascii_letters + string.digits) for i in range(12)))
Upvotes: 0
Reputation: 137
Here is the simple solution, go to your bolg/models.py
and first install pip install django-autoslug
Then import this
from django.db.models import CharField, Model
from autoslug import AutoSlugField
from django.utils.crypto import get_random_string
Here we are adding another extension called get_random_string
which will generate a random string every time you call it.
Then add this in your AddStory
{Your add post class}
#Defining a function to get random id every call
def randomid(self):
return(get_random_string(length=10))
# creating a custom slug to show in frontend.
news_slug = AutoSlugField(populate_from='randomid', unique = True, null= True, default=None)
Here I defined a function called randomid
which will return a 10 digit string on every call. Then I created a new field called news_slug which is coming from Django auto_slug extension, wich will populate from the randomid, and the URL must unique (ex: if it all 10 digit string are finished it will add -1,-2 so on ( ex: sxcfsf12e4-1), here null = true
means that this field can be empty so that autoslug can generate unique ID.
Then expose that news_slug
filed in API.
api_fields=[
APIField("news_slug"),
]
you can access all field like this /api/v2/pages/?type=blog.AddStory&fields=*
Here type=blog is your blog
app and AddStory
is your class.
Hope this helps, it took time for me to find out. More wagtail tutorials will come.
Upvotes: 0