imagefield django example

  1. Create a Django model with an ImageField:
from django.db import models

class YourModel(models.Model):
    image = models.ImageField(upload_to='images/')
  1. Run the migration to create the database table:
python manage.py makemigrations
python manage.py migrate
  1. In a Django form, use the ImageField in conjunction with the forms.ImageField widget:
from django import forms
from .models import YourModel

class YourModelForm(forms.ModelForm):
    class Meta:
        model = YourModel
        fields = ['image']
  1. In a Django view, process the form and save the image to the model:
from django.shortcuts import render, redirect
from .forms import YourModelForm

def your_view(request):
    if request.method == 'POST':
        form = YourModelForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('success_url')
    else:
        form = YourModelForm()
    return render(request, 'your_template.html', {'form': form})