Establishing a URL for the Django ImageField model attribute using a custom storage solution designed specifically for Azure Cloud Storage

I am encountering an issue with my Django web application. Users are able to upload images successfully, but for some reason the URLs of these images are not being set properly when stored in Azure Cloud Storage. As a result, when I try to display these images using the code snippet below in my template, all I see is a broken image:

{% if entry.image_file %}
<img src="{{ entry.image_file.url }}"></img><br>
{% endif %}

I have implemented a custom storage class in my models.py file as shown below. Can you help me identify what might be missing or causing this issue?

from django.db import models
import os
from django.conf import settings
from django.core.files.storage import Storage
from azure.storage.blob import BlobService

accountName = 'accname'
accountKey = 'acckey'

class OverwriteStorage(Storage):
    container = 'containername'
    account_name = accountName
    account_key = accountKey

    def __init__(self, account_name=None, account_key=None, container=None):

        # constructor logic here...

    # other methods defined here...

class Entry(models.Model):
    description = models.TextField(validators=[MaxLengthValidator(500)])
    submitted_on = models.DateTimeField(auto_now_add=True)
    image_file = models.ImageField(upload_to=upload_to_location, storage=OverwriteStorage(), null=True, blank=True)

I have referred to examples and documentation to create this custom storage class and implement the necessary URL method. However, it seems that the URL method is not being called as expected (I verified this with a print statement). Any insights on how to resolve this would be greatly appreciated!

Answer №1

In Azure Blob Storage, each Blob has a unique URL for access. The URL follows this format:

http://<your_storage_name>.blob.core.windows.net/<container_name>/<blob_name>
. You can directly view it in a browser if the access permission of the blob is set to public.

If your images in Blob Storage are not sensitive, you can simply set the access permission to public blob to allow public read access to the blobs in the container, while keeping the container properties and metadata private.

To address your issue, log in to the Azure management portal, navigate to the storage tab on the left sidebar, select your storage name from the list to access your storage management page, go to the CONTAINERS tab, choose the specific container, click on the EDIT button at the bottom, adjust the access permissions, and save the configuration by clicking OK:

https://i.stack.imgur.com/OymSp.png

By clicking on the container name, you can see the list of blobs within it. You can copy the URL of an item and check it in a browser.

If you want to display the images uploaded to Azure storage, make some modifications to the original code. In the custom storage class, ensure that the url() function returns the correct URL. For testing purposes, return the URL string directly:

def geturl(self, name):
    return '%s/%s/%s' % ('http://garyteststorage.blob.core.windows.net', 'mycontainer', name)

Modify the return of the _save() function to be the URL of the image class instead of the name:

url = self.geturl(name)
return url
#return name

In models.py:

def upload_path(instance, filename):
    return 'uploads-from-custom-storage-{}'.format(filename)

class Photo(models.Model):
    #description = models.TextField(validators=[MaxLengthValidator(500)])
    #submitted_on = models.DateTimeField(auto_now_add=True)
    image_file = models.ImageField(upload_to=upload_path, storage=OverwriteStorage(), null=True, blank=True )

Previously, the image name was saved in the database. After modification, the full URL of the blob will be stored.

Code snippet In view.py:

if form.is_valid():
    newImage = Photo(image_file = request.FILES['image_file'])
    newImage.save()
    imageurl = newImage.image_file
    html = "<img src=%s></img><br>" %imageurl
    # Redirect to the document list after POST
    return HttpResponse(html)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Bokeh for Interactive Time Series Visualization and Highlighting Specific Time Ranges

I am working on a time series plot and I want to add a layer that highlights specific ranges using glyphs. Here is an example: fig.quad(top=[10], bottom=[0], left=[0], right=[100], color="red", fill_alpha = 0.2) The user should be able to dynamically add ...

Build a Standalone Python GUI2Exe Application Using Py2Exe

Currently, I am attempting to transform my Python script into a standalone application using GUI2Exe. The script utilizes the selenium package, which is already installed. While the project compiles successfully and runs on the Python command line, it enco ...

Planck's law and frequency calculations

Exploring the frequency version of Planck's law has been quite a journey for me. Initially, I attempted to tackle this challenge on my own with the following code snippet: import numpy as np import matplotlib.pyplot as plt import pandas as pd import ...

Convert Ajax null value to NoneType in web2py

Every time I save information on a page, an AJAX request is sent with all the necessary data to be stored in the database. The format of this data looks similar to this example: {type: "cover", title: "test", description: null, tags: null} However, when ...

Challenges encountered when trying to use Python Selenium for web scraping

from selenium import webdriver import os os.chdir("C:\\Users\\czoca\\PycharmProjects\\pythonProject4") driver = webdriver.Chrome() driver.get("https://www.sitetoscrape.com/page1.html") driver.implicitly_wait(10) ele ...

What is the reasoning behind utilizing just x in the for loop instead of incorporating both x and y in the code?

What is the reasoning behind using only X in the for loop instead of both X and Y? Additionally, why are we applying reshape with 1, -1? # Create a loop to calculate Euclidean distances between each element in X and Y # Save the results in euclidean_dis ...

Steps for eliminating unicode characters from a dataset using Pandas in Python

My dataset named rssfeeds has some unusual characters, how can I remove these unicodes and replace them with their original values? Here is a link to view my dataset: https://i.stack.imgur.com/CtYG0.png Any help would be greatly appreciated. ...

To avoid errors, ensure that a QApplication is created before using a QPaintDevice with a QWidget

Currently, I'm in the process of converting an IRC client from Python 2.6 to 3.3 and have encountered a problem related to PyQt. Initially, the application used PyQt4, but now I am transitioning it to work with PyQt5. However, I am facing an error tha ...

Selenium operating within an Alpine 3.6 container

I am attempting to use Selenium on a Alpine 3.6 container (FROM alpine:3.6). This is what I'm trying in the container shell: apk update apk add python3 pip3 install -U selenium apk add chromium apk add chromium-driver Then, I run the following Pyth ...

SQLFORM that does not include a submit button

Currently working with the web2py framework, I am faced with a challenge in creating a SQLFORM without a submit button. The issue arises from having multiple forms on the page, some of which share common fields, making it impossible to use SQLFORM.factor ...

Ways to incorporate a timer for measuring code execution time

I recently developed a Python script that extracts product information from AliExpress. Check out the code below : from selenium.webdriver.edge.options import Options from selenium.webdriver.support import expected_conditions as EC from selenium.webdriv ...

Modifying the index value in a list within a Tower of Lists

Looking to implement a unique Queue in Python using this specific code snippet data = queue.Queue(maxsize=4) lists = [None] * 3 for i in range(4): data.put(lists) This code sets up a Queue containing 4 Lists, each with three None elements: > print( ...

The error message in Phyton states that only integers (or booleans) can be used as indices, but I specifically require floats for this operation

Encountering a persistent issue where I am unable to use dtype=np.int8 due to the requirement of precise floats for all arrays. Currently engaged in developing a simple model focusing on the spread of covid-19 infection. Experimenting with multiple numpy a ...

Execute a Python script in a separate file within Laravel framework

I have a directory containing a Python Selenium Appium script and a Laravel folder with the following path: mobile-automation laravel app.py My objective is to execute the shell script pytest -s app.py from within the Laravel framework. I have alrea ...

Utilizing FiPy to tackle the challenge of solving Fick's second law of diffusion within a one-dimensional sphere

Currently, I am attempting to solve the partial differential equation for the second law of diffusion for spheres using fipy. While reviewing the documentation, I noticed there is no example provided for this particular case. This has led me to question if ...

Initiate a Python reboot script within a separate command prompt's window

Is there a way to restart a different script in a separate shell? I have a script that sometimes gets stuck waiting to read email from Gmail and IMAP. From another script, I would like to restart the main one without interrupting the second script's e ...

Extracting odds data from various betting websites

I'm currently facing a challenge in my Python and Selenium web scraping project, focusing on extracting sports results from various webpages. The specific page I'm struggling with is this one. My goal is to generate a nested list structure. To i ...

I am eager to investigate why this method suddenly stops looping after processing the second record

I need to create a button that loops through all records and performs a method that generates a list of ranges between two fields. Then, it should remove another record from the list and place the value in the result field. I have implemented the code bel ...

What is the best way to sort a loop and keep the data for future use?

I'm currently in the process of scraping data from Amazon as part of a project I'm working on. So far, I have set up the following workflow: driver = webdriver.Chrome(executable_path=r"C:\Users\chromedriver.exe") driver.maxim ...

Having trouble finding a webpage element (button) with the ID 'next' using Python and Selenium

I recently delved into Python with Selenium to automate tasks, but I've hit a roadblock. My goal is to create a script that automatically clicks the 'next' button on a webpage. However, I'm facing difficulty in locating the element (but ...