How to Store Image Fields - bounswe/bounswe2024group11 GitHub Wiki

We'll use MySQL database with a Django framework.

Model Definition

Create a model to represent the image data along with its metadata. We'll use a BinaryField to store the image data.

# model.py
from django.db import models

class Image(models.Model):
    name = models.CharField(max_length=100)
    image_data = models.BinaryField()

Form for Image Upload

Create a form to handle image uploads.

# forms.py
from django import forms
from .models import Image

class ImageForm(forms.ModelForm):
    class Meta:
        model = Image
        fields = ['name', 'image_data']

View for Image Upload

Create a view to handle image uploads.

# views.py
from django.shortcuts import render, redirect
from .forms import ImageForm

def upload_image(request):
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('success')  # Redirect to a success page
    else:
        form = ImageForm()
    return render(request, 'upload.html', {'form': form})

Template for Image Upload Form (Frontend Part)

Create a template to render the image upload form.

<!-- upload.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Upload Image</title>
</head>
<body>
    <h2>Upload Image</h2>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Upload</button>
    </form>
</body>
</html>

⚠️ **GitHub.com Fallback** ⚠️