2

I have created a model called 'Video' and in the Video class there is a field called videoID. I want videoID to be a randomly generated string but in my solution, there has been some errors. Here is my solution:

models.py

from django.db import models
from django.contrib.auth.models import User
from other.video import generateVideoID

class Video(models.Model):
    videoID = models.TextField(default=generateVideoID(),editable=False)
    author = models.ForeignKey(User,on_delete=models.CASCADE, null=True)

As you can see in the videoID field I have set the default value to a function that returns a random string. This doesn't work because every time I create an object the videoID has the same string. This is the 'generateVideoID' function:

def generateVideoID():
    import random,string

    chars = string.ascii_letters+string.digits+"_-~"

    videoID = ""
    for i in range(12):
        videoID += random.choice(chars)
    return videoID

I have tried to use the 'init' method to set the videoID but that doesn't work. Can anyone help me?

2
  • Is there a specific reason you aren't using something that is readily available already, like a UUID? Commented Jun 12, 2020 at 15:45
  • @dfundako i didn't know it existed so i just made that function Commented Jun 12, 2020 at 15:47

2 Answers 2

2

Yes, but you should not call it, and furthermore it should be defined before you refer to it, so:

from django.db import models
from django.contrib.auth.models import User
from other.video import generateVideoID

class Video(models.Model):
    videoID = models.TextField(default=generateVideoID, editable=False)
    author = models.ForeignKey(User,on_delete=models.CASCADE, null=True)

so without parenthesis. If you add parenthesis, the function will be called, and the result will be used as default for all objects.

Sign up to request clarification or add additional context in comments.

Comments

2

Alternatively you could use the UUIDField:

from uuid import uuid4

class Video(models.Model):
    uuid = models.UUIDField(default=uuid4, editable=False, unique=True)
    author = models.ForeignKey(User,on_delete=models.CASCADE, null=True)

2 Comments

this works but i need to use the videoID in the URL
You should be able to use this the same way you were previously. You may need to cast the value to a str for some things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.