This is our Tutorial page!
Watch our most recent
YouTube video
Have you ever heard of NFT's? Of course you have! But do you know what you they are? Of course you don't :)
NFT stands for non-fungible token. An NFT is a ONE-OF-A-KIND digital asset that belongs to just one person. An NFT can be anything from artwork and collectibles through to tickets and deeds to a car.
The biggest trend at the time of writing this article is digital collectible artwork. These NFT's are created (minted) on a DLT (Distributed Ledger Technology) such as Ethereum or Hedera and then purchased as a collectable by the general public.
In this tutorial, I will demonstrate how you can easily create your own collection of NFT artwork using Django. We will also calculate the rarity of each collectable.
Don't want to read this tutorial? Okay, fine. I have put this video together for you.
Also, the code for this tutorial can be found in this GitHub repository. Just clone down the project from the did_nft repo, into your local development directory using the full-code branch:
git clone --branch full-code git@github.com:bobby-didcoding/did_nft.git
Okay, let's jump into it...
Syllabus:
This tutorial will focus on the following:
- Cloning the GitHub repository
- Create Artwork
- Configuring project
- Testing
Prerequisites:
We will be using Celery to handle the creating of NFTs via a task. Therefore, you will need to have Linux installed on your machine and have Redis installed.
Also, I will be using Adobe Photoshop in this tutorial to create the artwork layers.
Setup:
Firstly, Let's get our code.
Navigate to your development directory and create a new project directory. Open Visual Studio Code in your new directory.
The easiest way to do this is to click into the directory address and type 'cmd'.
This will open a new Command Prompt (cmd). To open Visual Studio Code you can use the following command in cmd:
mkdir nft && cd nft
code .
This will open visual code.
Open a new git terminal in Visual Studio Code and add the following commands:
git clone --branch main git@github.com:bobby-didcoding/did_nft.git .
Create Artwork:
Note: This project has some VERY basic artwork included. Feel free to design your own. This is how I created mine.
- Open up a new file in Photoshop that is 20 X 20 pixels.
- Zoom in by pressing Ctrl + '+'.
- Draw anything you like with the pencil tool.
- Now use the magic wand tool to select subject.
- Now add a vector mask.
- Export the image as a png.
- Now open your new png file in Photoshop.
- Select the subject, Press Shift + F5 to fill the shape and then export as a new file.
- Keep you artwork in named directories. This will help a lot in Django.
Project setup:
Most of the project is built as it is a basic Django config. Lets focus our time on the fun stuff.
Navigate to nft-generator/utils.py.
This is currently empty. We will use this file to manage our artwork traits in directories.
Add the following code to the file:
def createBaseDict():
return {
1: 'Green',
2: 'Red',
3: 'Blue',
4: 'Yellow',
}
def createBodyDict():
return {
1: 'Tone 1',
2: 'Tone 3',
3: 'Tone 3',
4: 'Tone 4',
}
def createHairDict():
return {
1: 'Tone 1',
2: 'Tone 3',
3: 'Tone 3',
4: 'Tone 4',
}
def createPantsDict():
return {
1: 'Dungeries',
2: 'Purple',
3: 'Blue',
4: 'Black',
}
def createTopDict():
return {
1: 'Cheque',
2: 'Red',
3: 'Blue',
4: 'Yellow',
}
def createPropDict():
return {
1: 'Dark Purple',
2: 'Purple',
3: 'None',
4: 'None',
}
def createBlingDict():
return {
1: 'Chain',
2: 'Bracelet',
3: 'None',
4: 'None',
}
You will notice that I am referencing my specific artwork by name and number. Make sure you alter the functions to match your artwork.
Now navigate to nft-generator/tasks.py
Another blank file! We will be using this to create our Celery task. Why Celery? Well this is all part of a tutorial and generating 100's of NFT's in a views Request/Response will slow things up.
Add the following code to tasks.py:
from .import utils
from .models import NoneFungibleToken
from PIL import Image
from django.conf import settings
from random import randint
from io import BytesIO
from django.core.files.uploadedfile import File
from celery import shared_task
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
def randomise():
return str(randint(1,4))
@shared_task(bind=True)
def create_nft(self, quantity):
base_dict = utils.createBaseDict()
body_dict = utils.createBodyDict()
hair_dict = utils.createHairDict()
top_dict = utils.createTopDict()
pants_dict = utils.createPantsDict()
prop_dict = utils.createPropDict()
bling_dict = utils.createBlingDict()
for nft in range(quantity):
nft_attributes = {}
base_key = randomise()
base = Image.open(f'{settings.STATIC_ROOT}/base/{base_key}.png')
nft_attributes["base"] = base_dict[int(base_key)]
body_key = randomise()
body = Image.open(f'{settings.STATIC_ROOT}/body/{body_key}.png')
nft_attributes["body"] = body_dict[int(body_key)]
hair_key = randomise()
hair = Image.open(f'{settings.STATIC_ROOT}/hair/{hair_key}.png')
nft_attributes["hair"] = hair_dict[int(hair_key)]
top_key = randomise()
top = Image.open(f'{settings.STATIC_ROOT}/top/{top_key}.png')
nft_attributes["top"] = top_dict[int(top_key)]
pants_key = randomise()
pants = Image.open(f'{settings.STATIC_ROOT}/pants/{pants_key}.png')
nft_attributes["pants"] = pants_dict[int(pants_key)]
prop_key = randomise()
prop = Image.open(f'{settings.STATIC_ROOT}/prop/{prop_key}.png')
nft_attributes["prop"] = prop_dict[int(prop_key)]
bling_key = randomise()
bling = Image.open(f'{settings.STATIC_ROOT}/bling/{bling_key}.png')
nft_attributes["bling"] = bling_dict[int(bling_key)]
# Paste/Merge Required PNGs, as layers on base
base.paste(body, (0, 0), body)
base.paste(hair, (0, 0), hair)
base.paste(top, (0, 0), top)
base.paste(pants, (0, 0), pants)
base.paste(prop, (0, 0), prop)
base.paste(bling, (0, 0), bling)
#create a new NFT object in db - with json attributes
new_nft = NoneFungibleToken()
new_nft.nft_attributes = nft_attributes
new_nft.save()
#Resize image to OpenSea market recommended size - "Resample Nearest" to retain resolution
resized_img = base.resize((300, 300), resample=Image.NEAREST)
image_io = BytesIO()
resized_img.save(image_io, "PNG")
name = f'Did Coding NFT #{new_nft.id}'
slug = f'didcoding-{new_nft.id}'
file_name = f'didcoding-{new_nft.id}.png'
image = File(image_io, name=file_name)
new_nft.image = image
new_nft.name = name
new_nft.slug = slug
new_nft.save()
We now need to set up our variables for the project. Open a terminal and use the following code to create a .env file:
cp .env.template .env
Your new .env file needs to look like this:
DEBUG=1
SECRET_KEY=**add_secret**
DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]
SQL_ENGINE=django.db.backends.postgresql
SQL_DATABASE=**db_name**
SQL_USER=**db_user_name**
SQL_PASSWORD=**your_password**
SQL_HOST=**host**
SQL_PORT=**port**
CELERY_BROKER=redis://127.0.0.1:6379
CELERY_BACKEND=django-db
Please go ahead and add the collect variables.
You now need to set up your virtual environment. Open a new terminal and use the following code to do this:
python -m venv env
cd env/scripts && activate && cd ../..
Your virtual env should now be up and running. Now use the following commands configure Django correctly:
pip install -r requirements.txt
python manage.py migrate
python manage.py collectstatic
That's it! All we need now is an active Redis server, a Celery worker and our Django project to be running.
Open a new Linux server and add the following:
redis-server
Note: leave this terminal open.
Now open another Linux server and add the following:
redis-cli
Note: leave this terminal open as well.
You now need to open a standard terminal, fire up your virtual environment (see above) and use the following code:
celery -A nft.celery worker --pool=solo -l info
You should not have any errors in your worker. You'll need to debug any unexpected errors.
Now lets fire up Django! open a new terminal and fire up your virtual environment. Use the following code to run a local server:
python manage.py createsuperuser
python manage.py runserver
Testing:
I'm calling it testing but let's just have a play and get creative.
Now that the server is running, visit http://127.0.0.1:8000/ with your Web browser. You should see our new web application.
You can access the built-in Admin page http://127.0.0.1:8000/admin with your Web browser.
Conclusion
We have successfully built a Django app that allows us to create large quantities of NFT artwork programmatically.
Start typing and press Enter to search