Share it on social media

Table of contents

Published: April 10, 2022 Last modified: May 11, 2022

Create NFT generator website with Django | py-avataaars + Django

The term NFT is spreading everywhere. For that, we will build an NFT website generator with Python. We choose the number of images we want to generate then it creates those unique images within a few seconds.



Requirements


  • Python 3.7 and above 🔗

  • Django 3.1 and above 🔗

  • py-avataaars 1.1.2  🔗

  • Django Tailwind  🔗

    NodeJS 🔗


Warning: I'm assuming that you're familiar with Django and Python. I won't cover the installation process, and I'll jump into generating avatar images using Python on a Django website.

If you're new to Django, watch THIS TUTORIAL about setting up a Django project onVScode. You will be able to follow along with this tutorial after watching that video first.

And for the installation of the tools, I’m using faster_dj_dev to automate everything for us.

Fix the “cairo” installation for Windows


I'm working on Ubuntu and so far I didn't face any errors. But for Windows users might face this error during using py-avataaars:

OSError: no library called "cairo" was found

Solution:

Download the UniConverter2 from here.



After installing it, try to find the dlls folder. It will be something like this:

C:\Program Files\UniConvertor-2.0rc5\dlls

The next step is adding the location of the dll file to the system path.

  • Start->Settings->Control Panel->System->Advanced->Environment Variables

  • Under System variables (the bottom part of the dialog), locate the Path variable

  • Click edit

  • Go to the end of Variable value and add C:\Program Files\UniConvertor-2.0rc5\dlls

  • Click OK on all the dialogs to save the new settings


The last step is opening a CMD command prompt as administrator then open Python prompt and run this command after installing it and the error should be gone.


from py_avataaars import PyAvataaar

py-avataaars: How it works?


It's a tool that allows you to generate a random avatar. This tool is a cartoon avatar maker tool, with the option to modify parts of the avatar with multiple parts.

To install it run this command:

pip install py-avataaars

Then you can create a 3-line program that generates a random avatar image for you.


from py_avataaars import PyAvataaar

avatar = PyAvataaar()
avatar.render_png_file('name.png')





But those three lines of code will generate that default avatar image, let’s try to take control over how the avatar should look like.


import py_avataaars as pa

avatar = pa.PyAvataaar(

style=pa.AvatarStyle.CIRCLE,

skin_color=pa.SkinColor.LIGHT,

hair_color=pa.HairColor.BROWN,

facial_hair_type=pa.FacialHairType.DEFAULT,

facial_hair_color=pa.HairColor.BLACK,

top_type=pa.TopType.SHORT_HAIR_SHORT_FLAT,

hat_color=pa.Color.BLACK,

mouth_type=pa.MouthType.SMILE,

eye_type=pa.EyesType.DEFAULT,

eyebrow_type=pa.EyebrowType.DEFAULT,

nose_type=pa.NoseType.DEFAULT,

accessories_type=pa.AccessoriesType.DEFAULT,

clothe_type=pa.ClotheType.GRAPHIC_SHIRT,

clothe_color=pa.Color.HEATHER,

clothe_graphic_type=pa.ClotheGraphicType.BAT,

)

avatar.render_png_file('avatar.png')


So in order to generate as much different avatars as possible, we need to get access to all the possible options and characters variations.

Here is the full list.



classes

Options

AvatarStyle

style=

AvatarStyle.CIRCLE

AvatarStyle.TRANSPARENT

SkinColor

skin_color=

SkinColor.TANNED

SkinColor.YELLOW

SkinColor.PALE

SkinColor.LIGHT

SkinColor.BROWN

SkinColor.DARK_BROWN

SkinColor.BLACK



HairColor

hair_color=

HairColor.AUBURN

HairColor.BLACK

HairColor.BLONDE

HairColor.BLONDE_GOLDEN

HairColor.BROWN

HairColor.BROWN_DARK

HairColor.PASTEL_PINK

HairColor.PLATINUM

HairColor.RED

HairColor.SILVER_GRAY



TopType

top_type=

TopType.NO_HAIR

TopType.EYE_PATCH

TopType.HAT

TopType.HIJAB

TopType.TURBAN

TopType.WINTER_HAT1

TopType.WINTER_HAT2

TopType.WINTER_HAT3

TopType.WINTER_HAT4

TopType.LONG_HAIR_BIG_HAIR

TopType.LONG_HAIR_BOB

TopType.LONG_HAIR_BUN

TopType.LONG_HAIR_CURLY

TopType.LONG_HAIR_CURVY

TopType.LONG_HAIR_DREADS

TopType.LONG_HAIR_FRIDA

TopType.LONG_HAIR_FRO

TopType.LONG_HAIR_FRO_BAND

TopType.LONG_HAIR_NOT_TOO_LONG

TopType.LONG_HAIR_SHAVED_SIDES

TopType.LONG_HAIR_MIA_WALLACE

TopType.LONG_HAIR_STRAIGHT

TopType.LONG_HAIR_STRAIGHT2

TopType.LONG_HAIR_STRAIGHT_STRAND

TopType.SHORT_HAIR_DREADS_01

TopType.SHORT_HAIR_DREADS_02

TopType.SHORT_HAIR_FRIZZLE

TopType.SHORT_HAIR_SHAGGY_MULLET

TopType.SHORT_HAIR_SHORT_CURLY

TopType.SHORT_HAIR_SHORT_FLAT

TopType.SHORT_HAIR_SHORT_ROUND

TopType.SHORT_HAIR_SHORT_WAVED

TopType.SHORT_HAIR_SIDES

TopType.SHORT_HAIR_THE_CAESAR

TopType.SHORT_HAIR_THE_CAESAR_SIDE_PART



FacialHairColor

facial_hair_color=

FacialHairColor.AUBURN

FacialHairColor.BLACK

FacialHairColor.BLONDE

FacialHairColor.BLONDE_GOLDEN

FacialHairColor.BROWN

FacialHairColor.BROWN_DARK

FacialHairColor.PLATINUM

FacialHairColor.RED



FacialHairType

facial_hair_type=

FacialHairType.DEFAULT

FacialHairType.BEARD_MEDIUM

FacialHairType.BEARD_LIGHT

FacialHairType.BEARD_MAJESTIC

FacialHairType.MOUSTACHE_FANCY

FacialHairType.MOUSTACHE_MAGNUM



ClotheType

clothe_type=

ClotheType.BLAZER_SHIRT

ClotheType.BLAZER_SWEATER

ClotheType.COLLAR_SWEATER

ClotheType.GRAPHIC_SHIRT

ClotheType.HOODIE

ClotheType.OVERALL

ClotheType.SHIRT_CREW_NECK

ClotheType.SHIRT_SCOOP_NECK

ClotheType.SHIRT_V_NECK



ClotheGraphicType

clothe_graphic_type=

ClotheGraphicType.BAT

ClotheGraphicType.CUMBIA

ClotheGraphicType.DEER

ClotheGraphicType.DIAMOND

ClotheGraphicType.HOLA

ClotheGraphicType.PIZZA

ClotheGraphicType.RESIST

ClotheGraphicType.SELENA

ClotheGraphicType.BEAR

ClotheGraphicType.SKULL_OUTLINE

ClotheGraphicType.SKULL



ClotheColor

clothe_color=

hat_color=

ClotheColor.BLACK

ClotheColor.BLUE_01

ClotheColor.BLUE_02

ClotheColor.BLUE_03

ClotheColor.GRAY_01

ClotheColor.GRAY_02

ClotheColor.HEATHER

ClotheColor.PASTEL_BLUE

ClotheColor.PASTEL_GREEN

ClotheColor.PASTEL_ORANGE

ClotheColor.PASTEL_RED

ClotheColor.PASTEL_YELLOW

ClotheColor.PINK

ClotheColor.RED

ClotheColor.WHITE



MouthType

mouth_type=

MouthType.DEFAULT

MouthType.CONCERNED

MouthType.DISBELIEF

MouthType.EATING

MouthType.GRIMACE

MouthType.SAD

MouthType.SCREAM_OPEN

MouthType.SERIOUS

MouthType.SMILE

MouthType.TONGUE

MouthType.TWINKLE

MouthType.VOMIT



NoseType

nose_type=

NoseType.DEFAULT

EyesType

eye_type=

EyesType.DEFAULT

EyesType.CLOSE

EyesType.CRY

EyesType.DIZZY

EyesType.EYE_ROLL

EyesType.HAPPY

EyesType.HEARTS

EyesType.SIDE

EyesType.SQUINT

EyesType.SURPRISED

EyesType.WINK

EyesType.WINK_WACKY



EyebrowType

eyebrow_type=

EyebrowType.DEFAULT

EyebrowType.DEFAULT_NATURAL

EyebrowType.ANGRY

EyebrowType.ANGRY_NATURAL

EyebrowType.FLAT_NATURAL

EyebrowType.RAISED_EXCITED

EyebrowType.RAISED_EXCITED_NATURAL

EyebrowType.SAD_CONCERNED

EyebrowType.SAD_CONCERNED_NATURAL

EyebrowType.UNI_BROW_NATURAL

EyebrowType.UP_DOWN

EyebrowType.UP_DOWN_NATURAL

EyebrowType.FROWN_NATURAL



AccessoriesType

accessories_type=

AccessoriesType.DEFAULT

AccessoriesType.KURT

AccessoriesType.PRESCRIPTION_01

AccessoriesType.PRESCRIPTION_02

AccessoriesType.ROUND

AccessoriesType.SUNGLASSES

AccessoriesType.WAYFARERS



Install Django and all the required tools


To avoid wasting time and install Django quickly, I’ve created a simple tool that automate such tedious tasks for me, you can check it from here, it’s open source.



Now to create the project, create a virtualenv and type the following commands:


$ python -m virtualenv venv
$ venv\Scripts\activate
$ pip install faster_dj_env
$ faster_dj_dev -cp -ct -cm -cs -im -a nft -i tailwind 

This installs the latest Django version which is verison 4.0.3. Creates an app called "nft". Also, it creates the "templates", "media" and "static" folders in the working directory.


Here are the main parts of the settings.py file




INSTALLED_APPS = [

...

"nft",

...

'tailwind',

'theme',

...

]

...

TEMPLATES = [

{

'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': [BASE_DIR / "templates"],

...

]

...

STATIC_URL = '/static/'

if not DEBUG:

STATIC_ROOT = BASE_DIR / 'static'

else:

STATICFILES_DIRS = [BASE_DIR / 'static']

MEDIA_ROOT = BASE_DIR / 'media'

MEDIA_URL = '/media/'

...

Note: I'm using the django-tailwind package, It's a great way of using the Tailwind CSS framework within a Django project.


And this is the base.html file, which all the other templates will inherit.




{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <title>{% block title %}
   
    {% endblock title %}</title>
    {% tailwind_css %}

</head>
<body>
    {% block content %}
   
    {% endblock content

   
</body>
</html>

Creating the collection and image models for our NFT project

Below we have two models that we need to store our generated files so we can download them later in one collection.


from django.db.models import (
    CharField, Model, ImageField, ManyToManyField, DateTimeField, ForeignKey, CASCADE
    )
from django.contrib.auth.models import User
class Image(Model):
    name = CharField(max_length=120)
    image = ImageField(null=True, blank=True)
    uploaded_on = DateTimeField(auto_now_add=True)

    def __str__(self):
            return self.name


class Collection(Model):
    user = ForeignKey(User, on_delete=CASCADE, related_name="collections", blank=True, null=True)
    name = CharField(max_length=120)
    images = ManyToManyField(Image)
    created_on = DateTimeField(auto_now_add=True)

    def __str__(self):
            return self.name



Create the collection form

As you saw on the website, we have only one form that represents the collection name and it has also the number of images we will create.


from django.forms import IntegerField, ModelForm
from nft.models import Image, Collection

class AvatarForm(ModelForm):
    quantity = IntegerField(max_value=1100)
    class Meta:
            model = Collection
            fields = ["name"]



Create a View for the home page

Now, let's update the views.py file to render the home page. To keep everything simple, I'll use the TemplateView.


from django.shortcuts import render
from django.views.generic import View, TemplateView
from nft.forms import AvatarForm
class HomeView(TemplateView):
    template_name = "home.html"
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["form"] = AvatarForm()
        return context


Integrate the Pyavataaars into Django


In order to create thousands of avatars, we need to use all the possible options we listed above, so I’ll create a file called options.py in the nft  app, it has all the possible options.


import py_avataaars


AVATAR_STYLE_OPTIONS = [

py_avataaars.AvatarStyle.CIRCLE,

py_avataaars.AvatarStyle.TRANSPARENT,

]


SKIN_COLOR_OPTIONS = [

py_avataaars.SkinColor.TANNED,

py_avataaars.SkinColor.YELLOW,

py_avataaars.SkinColor.PALE,

py_avataaars.SkinColor.LIGHT,

py_avataaars.SkinColor.BROWN,

py_avataaars.SkinColor.DARK_BROWN,

py_avataaars.SkinColor.BLACK,

]

HAIR_OPTIONS = [

py_avataaars.HairColor.AUBURN,

py_avataaars.HairColor.BLACK,

py_avataaars.HairColor.BLONDE,

py_avataaars.HairColor.BLONDE_GOLDEN,

py_avataaars.HairColor.BROWN,

py_avataaars.HairColor.BROWN_DARK,

py_avataaars.HairColor.PASTEL_PINK,

py_avataaars.HairColor.PLATINUM,

py_avataaars.HairColor.RED,

py_avataaars.HairColor.SILVER_GRAY,

]

TOP_OPTIONS = [

py_avataaars.TopType.NO_HAIR,

py_avataaars.TopType.EYE_PATCH,

py_avataaars.TopType.HAT,

py_avataaars.TopType.HIJAB,

py_avataaars.TopType.TURBAN,

py_avataaars.TopType.WINTER_HAT1,

py_avataaars.TopType.WINTER_HAT2,

py_avataaars.TopType.WINTER_HAT3,

py_avataaars.TopType.WINTER_HAT4,

py_avataaars.TopType.LONG_HAIR_BIG_HAIR,

py_avataaars.TopType.LONG_HAIR_BOB,

py_avataaars.TopType.LONG_HAIR_BUN,

py_avataaars.TopType.LONG_HAIR_CURLY,

py_avataaars.TopType.LONG_HAIR_CURVY,

py_avataaars.TopType.LONG_HAIR_DREADS,

py_avataaars.TopType.LONG_HAIR_FRIDA,

py_avataaars.TopType.LONG_HAIR_FRO,

py_avataaars.TopType.LONG_HAIR_FRO_BAND,

py_avataaars.TopType.LONG_HAIR_NOT_TOO_LONG,

py_avataaars.TopType.LONG_HAIR_SHAVED_SIDES,

py_avataaars.TopType.LONG_HAIR_MIA_WALLACE,

py_avataaars.TopType.LONG_HAIR_STRAIGHT,

py_avataaars.TopType.LONG_HAIR_STRAIGHT2,

py_avataaars.TopType.LONG_HAIR_STRAIGHT_STRAND,

py_avataaars.TopType.SHORT_HAIR_DREADS_01,

py_avataaars.TopType.SHORT_HAIR_DREADS_02,

py_avataaars.TopType.SHORT_HAIR_FRIZZLE,

py_avataaars.TopType.SHORT_HAIR_SHAGGY_MULLET,

py_avataaars.TopType.SHORT_HAIR_SHORT_CURLY,

py_avataaars.TopType.SHORT_HAIR_SHORT_FLAT,

py_avataaars.TopType.SHORT_HAIR_SHORT_ROUND,

py_avataaars.TopType.SHORT_HAIR_SHORT_WAVED,

py_avataaars.TopType.SHORT_HAIR_SIDES,

py_avataaars.TopType.SHORT_HAIR_THE_CAESAR,

py_avataaars.TopType.SHORT_HAIR_THE_CAESAR_SIDE_PART

]


FACIAL_HAIR_COLOR_OPTIONS = [

py_avataaars.HairColor.AUBURN,

py_avataaars.HairColor.BLACK,

py_avataaars.HairColor.BLONDE,

py_avataaars.HairColor.BLONDE_GOLDEN,

py_avataaars.HairColor.BROWN,

py_avataaars.HairColor.BROWN_DARK,

py_avataaars.HairColor.PLATINUM,

py_avataaars.HairColor.RED

]


FACIAL_HAIR_TYPE_OPTIONS = [

py_avataaars.FacialHairType.DEFAULT,

py_avataaars.FacialHairType.BEARD_MEDIUM,

py_avataaars.FacialHairType.BEARD_LIGHT,

py_avataaars.FacialHairType.BEARD_MAJESTIC,

py_avataaars.FacialHairType.MOUSTACHE_FANCY,

py_avataaars.FacialHairType.MOUSTACHE_MAGNUM,

]


CLOTHE_TYPE_OPTIONS = [

py_avataaars.ClotheType.BLAZER_SHIRT,

py_avataaars.ClotheType.BLAZER_SWEATER,

py_avataaars.ClotheType.COLLAR_SWEATER,

py_avataaars.ClotheType.GRAPHIC_SHIRT,

py_avataaars.ClotheType.HOODIE,

py_avataaars.ClotheType.OVERALL,

py_avataaars.ClotheType.SHIRT_CREW_NECK,

py_avataaars.ClotheType.SHIRT_SCOOP_NECK,

py_avataaars.ClotheType.SHIRT_V_NECK

]


CLOTHE_GRAPHIC_TYPE_OPTIONS = [

py_avataaars.ClotheGraphicType.BAT,

py_avataaars.ClotheGraphicType.CUMBIA,

py_avataaars.ClotheGraphicType.DEER,

py_avataaars.ClotheGraphicType.DIAMOND,

py_avataaars.ClotheGraphicType.HOLA,

py_avataaars.ClotheGraphicType.PIZZA,

py_avataaars.ClotheGraphicType.RESIST,

py_avataaars.ClotheGraphicType.SELENA,

py_avataaars.ClotheGraphicType.BEAR,

py_avataaars.ClotheGraphicType.SKULL_OUTLINE,

py_avataaars.ClotheGraphicType.SKULL

]


CLOTHE_COLOR_OPTIONS = [

py_avataaars.Color.BLACK,

py_avataaars.Color.BLUE_01,

py_avataaars.Color.BLUE_02,

py_avataaars.Color.BLUE_03,

py_avataaars.Color.GRAY_01,

py_avataaars.Color.GRAY_02,

py_avataaars.Color.HEATHER,

py_avataaars.Color.PASTEL_BLUE,

py_avataaars.Color.PASTEL_GREEN,

py_avataaars.Color.PASTEL_ORANGE,

py_avataaars.Color.PASTEL_RED,

py_avataaars.Color.PASTEL_YELLOW,

py_avataaars.Color.PINK,

py_avataaars.Color.RED,

py_avataaars.Color.WHITE

]


MOUTH_TYPE_OPTIONS = [

py_avataaars.MouthType.DEFAULT,

py_avataaars.MouthType.CONCERNED,

py_avataaars.MouthType.DISBELIEF,

py_avataaars.MouthType.EATING,

py_avataaars.MouthType.GRIMACE,

py_avataaars.MouthType.SAD,

py_avataaars.MouthType.SCREAM_OPEN,

py_avataaars.MouthType.SERIOUS,

py_avataaars.MouthType.SMILE,

py_avataaars.MouthType.TONGUE,

py_avataaars.MouthType.TWINKLE,

py_avataaars.MouthType.VOMIT

]


EYE_TYPE_OPTIONS = [

py_avataaars.EyesType.DEFAULT,

py_avataaars.EyesType.CLOSE,

py_avataaars.EyesType.CRY,

py_avataaars.EyesType.DIZZY,

py_avataaars.EyesType.EYE_ROLL,

py_avataaars.EyesType.HAPPY,

py_avataaars.EyesType.HEARTS,

py_avataaars.EyesType.SIDE,

py_avataaars.EyesType.SQUINT,

py_avataaars.EyesType.SURPRISED,

py_avataaars.EyesType.WINK,

py_avataaars.EyesType.WINK_WACKY

]


EYE_BROW_TYPE_OPTIONS = [

py_avataaars.EyebrowType.DEFAULT,

py_avataaars.EyebrowType.DEFAULT_NATURAL,

py_avataaars.EyebrowType.ANGRY,

py_avataaars.EyebrowType.ANGRY_NATURAL,

py_avataaars.EyebrowType.FLAT_NATURAL,

py_avataaars.EyebrowType.RAISED_EXCITED,

py_avataaars.EyebrowType.RAISED_EXCITED_NATURAL,

py_avataaars.EyebrowType.SAD_CONCERNED,

py_avataaars.EyebrowType.SAD_CONCERNED_NATURAL,

py_avataaars.EyebrowType.UNI_BROW_NATURAL,

py_avataaars.EyebrowType.UP_DOWN,

py_avataaars.EyebrowType.UP_DOWN_NATURAL,

py_avataaars.EyebrowType.FROWN_NATURAL

]


ACCESSORIES_OPTIONS = [

py_avataaars.AccessoriesType.DEFAULT,

py_avataaars.AccessoriesType.KURT,

py_avataaars.AccessoriesType.PRESCRIPTION_01,

py_avataaars.AccessoriesType.PRESCRIPTION_02,

py_avataaars.AccessoriesType.ROUND,

py_avataaars.AccessoriesType.SUNGLASSES,

py_avataaars.AccessoriesType.WAYFARERS

]

And to keep my code clean, I’ll create another file that has all the functions I’ll use to generate the images. I’ll name it utils.py and it will be in the nft folder too.


import multiprocessing

import py_avataaars

from django.shortcuts import render

from nft.forms import AvatarForm

from nft.models import Collection, Image

import os, random, time

from django.core.files import File

from multiprocessing import Pool

from functools import partial

import threading

from .options import *

def generate_random_avatar(filepath):

avatar = py_avataaars.PyAvataaar(

style=random.choice(AVATAR_STYLE_OPTIONS),

skin_color=random.choice(SKIN_COLOR_OPTIONS),

hair_color=random.choice(HAIR_OPTIONS),

facial_hair_type=random.choice(FACIAL_HAIR_TYPE_OPTIONS),

facial_hair_color=random.choice(FACIAL_HAIR_COLOR_OPTIONS),

top_type=random.choice(TOP_OPTIONS),

hat_color=random.choice(SKIN_COLOR_OPTIONS),

mouth_type=random.choice(MOUTH_TYPE_OPTIONS),

eye_type=random.choice(EYE_TYPE_OPTIONS),

eyebrow_type=random.choice(EYE_BROW_TYPE_OPTIONS),

nose_type=py_avataaars.NoseType.DEFAULT,

accessories_type=random.choice(ACCESSORIES_OPTIONS),

clothe_type=random.choice(CLOTHE_TYPE_OPTIONS),

clothe_color=random.choice(CLOTHE_COLOR_OPTIONS),

clothe_graphic_type=random.choice(CLOTHE_GRAPHIC_TYPE_OPTIONS),

)

avatar.render_png_file(filepath)



def create_collection_images(collection, i):

name = collection.name

filename = f'{name}-avatar-{i}'

filepath = f"{filename}.png"

generate_random_avatar(filepath)

img = Image.objects.create(name=filename)

img.image.save(filepath, File(open(filepath, 'rb')), save=True)

img.save()

collection.images.add(img)

os.remove(filepath)

collection.save()

return collection


def generate_avatars(request, context):

context = {}

if request.method == "POST":

form = AvatarForm(request.POST or None)

if form.is_valid():

collection = form.save()

quantity = form.cleaned_data.get("quantity")

for i in range(quantity):

thread = threading.Thread(name="thread", target=create_collection_images, args=[collection, i])

thread.daemon = True

thread.start()

time.sleep(0.1)



context.update({

"collection":collection

})

return context

How it works?

For the generate_random_avatar(filepath) is quite simple, we provide the file path where we want to save the generated image and of course the name of the file and we use the random module to randomly choose character options for each avatar, this way we will make sure to create unique images each time we generate a new collection.


The second function (create_collection_images(collection, i), will create a new collection object (model object) to save it in the database. So if we will generate 50 avatars in a collection named pack, the program will create a loop and create 50 images, in each loop it calls this function; It creates a new Image object and name it based on the collection name and save it in the given path.


And finally , (generate_avatars(request, context)) this one will take the quantity input from the template and use the previous function to create a collection with that number of images. And I’m using the multithreading the speedup the process, otherwise generating thousand image will take 1000 seconds at least which of course we should avoid.


Later on we will use this function on the views.py file.

The HTML templates used to generate NFT images


I'm using the below form to get the quantity and the name of the collection from the user.


<!--partials/generate-avatar-form.html-->

{% load tailwind_filters %}

{% load static %}

<div class="space-y-6 ">

<h1 class="text-2xl font-semibold text-gray-800 uppercase lg:text-3xl">

Generate NFT collection of images

</h1>

<form class="w-full" method="POST" action=".">

{% csrf_token %}

{{ form|crispy }}

<div class="flex justify-between items-center">

<button id="submit-button" type="submit" class="ml-auto w-full p-4 text-center text-xs font-medium text-white uppercase transition-colors duration-200 transform bg-blue-600 rounded-md lg:w-auto hover:bg-blue-500 focus:outline-none focus:bg-blue-500">

Generate

</button>

</div>

</form>

</div>


And here the HTML part where I display the results of the generated avatars.


{% load static %}


<!--partials/results.html-->

<section class="container p-6 mx-auto " id="results">

<h2 class="text-xl font-medium text-gray-800 capitalize dark:text-white md:text-2xl">Results</h2>

<div class="flex items-center justify-center">

<div class="{% if collection %}grid gap-8 mt-8 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4{% else %}flex justify-center items-center{% endif %}">

{% for result in collection.images.all %}

<div class="w-full max-w-xs text-center">

<img class="object-cover object-center w-full h-48 mx-auto rounded-lg" src="{{ result.image.url }}" alt="avatar"/>

</div>

{% empty %}

<img class="object-center transform scale-50" src="{% static 'empty.png' %}" alt="empty resulsts">

{% endfor %}


</div>

</div>

</section>

Update the views.py





Then we need to update the views.py file so we can render the result in the template.


from django.shortcuts import render

from django.views.generic import View, TemplateView

from requests import post

from nft.forms import AvatarForm

from .utils import generate_avatars

class HomeView(TemplateView):

template_name = "home.html"

def get_context_data(self,**kwargs):

context = super().get_context_data(**kwargs)

context["form"] = AvatarForm()

return context

def post(self, request, *args, **kwargs):

context = self.get_context_data(**kwargs)

context = generate_avatars(self.request, context)

context["form"] = AvatarForm()

return self.render_to_response(context)



We simply use the last function in the utils.py file to generate the required number of avatars based on the use inputs.

And for the home template, here is it:




{% extends 'base.html' %}

{% block content %}

<div class="flex min-h-screen w-full gap-6 p-4" id="content">

<div class="min-h-screen w-1/3 shadow-lg p-2">

{% include "partials/generate-avatar-form.html" %}

</div>

<div class="min-h-screen w-2/3 shadow-lg p-2">

{% include "partials/results.html" %}

</div>

</div>

{% endblock content %}

The final result (show case)





Please feel free to comment below if something went wrong or if you have any questions.



476 0
Selmitech

This is Selmi Abderrahim, the author and the admin of SelmiTech blog.

Subscribe to our mail list

No comments yet!