Mohammad Fathi Rahman
Mohammad Fathi Rahman

Reputation: 137

Add UID or Unique ID in Wagtail/Django

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

Answers (2)

Rich - enzedonline
Rich - enzedonline

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)))
  • AutoSlugField is part of django_extensions
  • AutoSlugField has a built in slugify_function to generate the slug, you can override that just by declaring your own in the class
  • This slugify_function will generate a random 12 alpha-numeric character string including upper/lower case. Permutations are (I think) 1 e21 so chances of guessing are extremely slim.

Upvotes: 0

Mohammad Fathi Rahman
Mohammad Fathi Rahman

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

Related Questions