How to encrypt data in django

Viewed 266

As we know that we had an id in Django for each item in models by using which we can access that item. Now I want to encrypt that while sending to the frontend so that the user can't enter random id in URL to access any note. So how can I encrypt that here is what i want

url should look thsi = notes.com/ldsfjalja3424wer0ew8r0 not like this = notes.com/45

class Note(models.Model):
  title = models.char
  id = model.primary

 
  def create_encryptkey():

And can be decoded in views if needed for any purpose for example to get exact id

Thanks!

1 Answers

Without encryption, use UUIDField to get url like:

http://localhost:8000/notes/8eb81c9b-c0db-4603-8479-37b9ea13a274

import uuid
from django.db import models

class Note(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4)
    title = models.CharField()

Update: If you want a version without dash, you can use a custom function:

import uuid
from django.db import models

def myuuid():
    return uuid.uuid4().hex

class Note(models.Model):
    id = models.UUIDField(primary_key=True, default=myuuid)
    title = models.CharField()
Related