Search code examples
pythondjangoimagesvgpath

How do I dynamically access barcode image I saved in a folder in Django


I don't seem to understand how to get an image of barcode I render and save into the template. I am saving the code with, description and the id, adding a little dynamism to it. My problem now is how to point to the image from the HTML template or if there is a better way to do this.

Here is my code:

def barcode(request, stock_id):
    obj = get_object_or_404(Stock, id=stock_id)
    d = utility.MyBarcodeDrawing(obj.description,)
    d.save(formats=['svg','img'],outDir='static_root/media',fnRoot='%s_%d' %(obj.description, stock_id)) 
    barcodePicUrl = "barcode/%s_%d" %(obj.description, stock_id)
    print(obj.description)
    return render_to_response('barcode.html', {'url':barcodePicUrl,'obj':obj})

Solution

  • def barcode(request, stock_id):
        obj = get_object_or_404(Stock, id=stock_id)
    
        #create a path barcode here
        barcode_path = 'static_root/media',fnRoot='%s_%d' %(obj.description, stock_id))
    
        d = utility.MyBarcodeDrawing(obj.description,)
    
        d.save(formats=['svg','img'],outDir= barcode_path) #pass it as variable
        #barcodePicUrl = "barcode/%s_%d" %(obj.description, stock_id)
        print(obj.description)
        return render_to_response('barcode.html', {'url':barcode_path,'obj':obj})
    

    The rigth way to solve this is using database for save the barcode path. Edit if necessary and try it,