How to Generate Barcode in Django?

Published On: 05/08/2022 | Category: Django


Hi Dev,

This is a short guide on django generate barcode. We will look at example of how to generate barcode in django. you can understand a concept of how to create barcode in django. we will help you to give example of how to save generated barcode in django.

In this example, we will generate a barcode using python-barcode package. I will give you a very simple example of generating Barcode with django.

Let's see the below step and you can generate bar code in your django projects as well.

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python3 manage.py startapp core
Step 3 : Update setting.py

In this step we require to do two things in our settings.py file, one is to configure our media folder. Add the below lines to your settings.py file:

Next, you need to add it in the settings.py file as follows:

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]

...
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
Step 4 : Install python-barcode Library

In this step next, we’ll use a python library for generating barcode called python-barcode as well.As the barcode will be generated in the form of images we’ll make use of the Pillow library as well.

pip install python-barcode
pip install Pillow
Step 5 : Database Setup

Next step, we will modify the settings.py file and update the database settings to configure the mydb database:

settings.py
DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
        'USER':'root',  
        'PASSWORD':'root',  
        'HOST':'localhost',  
        'PORT':'3306'  
    }  
}  
Step 6: Create a Model

In this step we will require the database model for storing contacts.Open the cropper/models.py file and add the following code:

cropper/models.py
from django.db import models
import barcode
from barcode.writer import ImageWriter
from io import BytesIO
from django.core.files import File


class Customer(models.Model):
    name = models.CharField(max_length=50)
    barcode = models.ImageField(upload_to='barcodes/', blank=True)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        COD128 = barcode.get_barcode_class('code128')
        rv = BytesIO()
        code = COD128(f'{self.name}', writer=ImageWriter()).write(rv)
        self.barcode.save(f'{self.name}.png', File(rv), save=False)
        return super().save(*args, **kwargs)

After creating these model, you need to create migrations using the following command:

Step 7 : Create a Migrations
python manage.py makemigrations

After successfully run the above command go to the cropper/migrations/0001_initial.py

cropper/migrations/0001_initial.py
# Generated by Django 3.2.6 on 2022-08-04 07:34

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Customer',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=50)),
                ('barcode', models.ImageField(blank=True, upload_to='barcodes/')),
            ],
        ),
    ]

Next, you need to migrate your database using the following command:

python manage.py migrate
Step 8 : Update the Admin.py File

So, in this step let’s register the model in the admin site and test it out. in admin.py we add the following lines.

core/admin.py
from .models import Customer

admin.site.register(Customer)
Step 9 : Creating URLs

Next, we will require the modify the urls.py your root preoject folder lets update the file.

example/urls.py
from django.conf import settings
from djano.conf.urls.static import static

urlpatterns = [
   path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the address with a web browser.

http://localhost:8000/admin/

I Hope It will help you....