1. Skip to navigation
  2. Skip to content

Regenerate Secret Key

I had a need to generate a new secret key for a Django project that I’m working on. Often when I start a new project I’ll just copy an existing project template that I have which has all the bits and pieces in the right places. This helps me to get going quickly without a lot of fuss. Although when doing so I always need a new SECRET_KEY for the settings file. Instead of doing it manually this time, I decided to create a new custom management command and make it part of my global management command extensions project. For doing this I just inherited from the NoArgsCommand and extracted the logic for creating the secret key from the startproject command in the Django source.


from random import choice
from django.core.management.base import NoArgsCommand

class Command(NoArgsCommand):
    help = "Generates a new SECRET_KEY that can be used in a project settings file." 

    requires_model_validation = False
    can_import_settings = True

    def handle_noargs(self, **options):
        return ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])