Skip to content

How to Store Image Fields

Yunus Kağan Aydın edited this page Apr 27, 2024 · 1 revision

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>

BOUNSWE2024 - G11

Logo Turquiz App

⏳ Status

  • Implementation Phase 1
  • Design
  • Scenarios & Mockups
  • Software Requirements Specification
  • Forming the Team

🧑🏼‍💻 Team

📝 Diagrams

📆 Lab Reports

📆 Meeting Notes

📍 Milestones

📚 User Scenarios / Stories

📚 Resources

🔎 Research

🗂️ Templates

Clone this wiki locally