Published: Aug. 5, 2019 by lukemakin |  estimated reading time: 7 minutes
In this tutorial we'll cover a practical topic regarding the upgrade of our account via activation codes with Django. Hopefully you all know the concept, but just to be sure, let's specify some details. On our website, a user will have a form to ener the code. If the code is valid, the price of i.e. products to buy or subscription, will be automatically decreased based on the amount of the discount.

This will be a 2 part tutorial. In this one we will create files: and (where we will handle django signals), in the next one we will cover,, and templates.

Let's get started with coding!

Create a django project with any given name and an app named 'codes'. Next create a file within the codes app called Before we write the actual code let's make an assumption, that our code should be 12 characters long and consist of capitalized letters and numbers only.

Let's take a look at two ways of accomplishing the same result. The first version is a little bit longer, and requires creating a list of all the characters. We'll put this list outside the function in case if we would like to use it somewhere else. Next let's write the function itself and within it's first line, we will shuffle the list. Then with the use of list comprehension we'll create a list of 12 characters (limiting it with slicing [:12]). As final step we'll need to join the created list into a string and return it.

import random

el = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

def random_code():
code = [str(x) for x in el[:12]]
str_code = ''.join(code)

return str_code

The shorter version can be done with the use of uuid (universally unique identifier), however we'll need to adjust this soultion because running uuid.uuid4() itself doesn't provide us with the desired outcome (i.e. a463749d-09d0-4948-949a-5b4b7b155fa5). 

import uuid

def random_code():
code = str(uuid.uuid4())[:12].replace('-', '').upper()
return code

So what happened here? First of all we made sure that the output will be a string type data. In the same way as above - with the use of slicing [:12] we limited the number of characters to 12. Next we got rid off the dashes and capitalized the string output assigned to code variable.

Let's now take a look at

from django.db import models
from .utils import random_code
from django.db.models.signals import pre_save
from django.contrib.auth.models import User
from django.dispatch import receiver

class Code(models.Model):
name = models.CharField(max_length=12, unique=True, blank=True)
discount = models.PositiveIntegerField(default=0)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)

def __str__(self):

@receiver(pre_save, sender=Code)
def pre_save_code(sender, instance, *args, **kwargs):
code = random_code() = code

In our model we have specified name (wi'll be generated automaticaly), the amount of discount (i.e. 25 as 25%), and date points for update and creation.

As next step, from we imported our random_code() function and assigned it to the code variable in a pre_save signal. Before saving the model, our code will be generated based on random_code() function.

That is it! See you in part 2 where we will continue from here.

To view additional content login or create a free account
Share your thoughts

No comments yet...

Signup to the newsletter
To get the latest updates from pyplane
© copyright 2019