Home > Software design >  how to check if input for barcode is valid using django?
how to check if input for barcode is valid using django?

Time:06-27

I made an app to generate barcodes using python-barcode library (Python)(django framework)

and there's two fields

1 - to let the user input the number that will used for generate the barcode

2 - options to let the user select which type of barcode he wants

for now everything work fine it's generating the barcodes

but some of the barcodes have its specific types of inputs like 12 digits or 8 digits and so on

so how to check the inputs if its valid for that type of barcode or not?, then show error messages if it's wrong, or succes message if it generated fine

I know I can use messages form django itself but how I can implement it with checking function?

for views.py

from sre_constants import SUCCESS
from django.http import HttpResponse
from django.shortcuts import redirect, render
import barcode
from barcode.writer import ImageWriter
import tempfile
from django.contrib import messages


def index(request):
   context = {'barcode_types':barcode.PROVIDED_BARCODES}
   return render(request, 'index.html',context)

def generate_barcode(request):
   inputs = request.POST['inputs']
   types = request.POST['types']
   barcode_class = barcode.get_barcode_class(types)
   file = tempfile.NamedTemporaryFile()
   code = barcode_class(inputs,writer=ImageWriter())
   file_path = code.save(file.name)
   response = HttpResponse(open(file_path,'rb').read(), headers={'Content-Type': 'image/png','Content-Disposition': 'attachment; filename="' inputs '.png"'})
return response

CodePudding user response:

You should use forms inorder to validate user inputs

  • You can set options on form inputs like max_length, min_length
  • You can limit users to specific data types:
    • integer: IntegerField
    • short text: CharField
    • floating point numbers: FloatField
  • You can make a field required: required=True
  • You can give them some limited choices to choose from: ChoiceField
  • You can use additional validators

If I understood your question correctly, you need to validate the inputs based on types, so according to the documentation, you need to overwrite the clean function to perform multi-field validation

The form subclass’s clean() method can perform validation that requires access to multiple form fields. This is where you might put in checks such as “if field A is supplied, field B must contain a valid email address”. This method can return a completely different dictionary if it wishes, which will be used as the cleaned_data.

here is an example:

# forms.py

from django import forms
from django.core.exceptions import ValidationError

BARCODE_TYPES =(
    # (value, display)
    ("Code39", "Code 39"),
    ("Code128", "Code 128"),
    ("PZN7", "PZN 7"),
    ("EuropeanArticleNumber13", "EAN-13"),
    ("EuropeanArticleNumber8", "EAN-8"),
    ("JapanArticleNumber", "JAN"),
    ("InternationalStandardBookNumber13", "ISBN-13"),
    ("InternationalStandardBookNumber10", "ISBN-10"),
    ("InternationalStandardSerialNumber", "ISSN"),
    ("UniversalProductCodeA", "UPC-A"),
    ("EuropeanArticleNumber14", "EAN-14"),
    ("Gs1_128", "Gs1-128"),
)
class BarcodeForm(forms.Form):
    # You can use max_lenth, min_length, ....
    inputs = forms.CharField(label='Bacode data', max_length=100, required=True)
    types = forms.ChoiceField(label='The Bracode type', choices=BARCODE_TYPES, required=True)

    def clean(self):
        cleaned_data = super().clean()
        inputs = cleaned_data.get("inputs")
        types = cleaned_data.get("types")

        if types == "Code39":
            # validate input for Code39
            # Raise error with the message you want on invalid input:
            raise ValidationError("Invalid input for Code 39 barcode type, you should ......")
        elif types == "Code128":
            # validate input for Code128
            # Raise error with the message you want on invalid input:
            raise ValidationError("Invalid input for Code 128 barcode type, you should ......")
        # .....

Then use this form in your views like this: (docs)

# views.py
from .forms import BarcodeForm

def generate_barcode(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = BarcodeForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
             # process the data in form.cleaned_data as required
     # .....
  • Related