I'm currently working on a Django application hosted locally that accepts user-uploaded images. The images are stored successfully, but I'm facing challenges in generating a publicly accessible URL for these uploaded images. The ultimate goal is to feed this URL into the replicate.com API endpoint.
Here's a brief overview of my process:
- User uploads an image via the Django app.
- The image is stored locally on the server.
- Need to generate a publicly accessible URL for the uploaded image. views.py:
from django.shortcuts import render
import os
import replicate
from .forms import ImageUploadForm
def index(request):
if request.method == 'POST':
form = ImageUploadForm(request.POST, request.FILES)
if form.is_valid():
image_instance = request.FILES['image']
file_url = handle_uploaded_file(image_instance)
response = run_replicate(file_url)
output_url = response[0]
context = {'output_url': output_url}
return render(request, 'core/results.html', context)
else:
form = ImageUploadForm()
return render(request, 'core/index.html', {'form': form})
def handle_uploaded_file(uploaded_file):
os.makedirs('images/new', exist_ok=True)
file_path = os.path.join('images/new', uploaded_file.name)
with open(file_path, 'wb+') as destination:
for chunk in uploaded_file.chunks():
destination.write(chunk)
file_url = file_path.replace("\\", "/")
file_url = "https://replit.com/@mashudhassandev/ChatgptImgGen#" + file_url
return file_url
def run_replicate(file_content):
model_id = 'jagilley/controlnet-canny:aff48af9c68d162388d230a2ab003f68d2638d88307bdaf1c2f1ac95079c9613'
response = replicate.run(
model_id,
input={
'image': open(file_content, "rb"),
'prompt': 'hyperrealistic portrait, photograph, real person'
})
return response
How can I effectively create a publicly accessible URL for the uploaded images in Django? Any insights, code snippets, or best practices would be greatly appreciated.