Gaurav Tomer
Gaurav Tomer

Reputation: 731

Image field didn't get saved, raises error 'This field is required'

models.py:

from django.db import models
from django.contrib.auth.models import User


class Electronics(models.Model):
    ELEC_CHOICES = (
        ('LAP', 'Laptops'),
        ('MOB', 'Mobiles'),
        ('WAT', 'Watches'),
        ('CAM', 'Camera'),
    )
    elec_name = models.CharField(max_length=3, choices=ELEC_CHOICES)
    elec_image = models.ImageField('Label', upload_to='C:/Users/User/Desktop/')
    elec_price = models.IntegerField('Price')
    elec_stock  = models.BooleanField(default=False)

forms.py:

from django import forms
from django.forms import ModelForm
from .models import Electronics


class ElectronicsForm(ModelForm):
    class Meta:
        model = Electronics
        fields = '__all__'

views.py:

from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Electronics
from .forms import ElectronicsForm

# Create your views here.

def eleclist(request):
    elec = Electronics.objects.order_by('elec_name')
    return render(request, 'index.html', {'elec': elec})

def elecadd(request):
    if request.method == 'POST':
        form = ElectronicsForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('shopp:eleclist'))
        else:
        print(form.errors)
    else:
        form = ElectronicsForm()

    return render(request, 'add.html', {'form': form})

my add.html:

<html>
<head><title>Electronics</title></head>
<body>
    <form method = "post">
        {% csrf_token %}
        {{form.as_p}}
        <input type="submit" name="submit" value="create">
    </form>
</body>     
</html>

I'am first time trying to upload an image using django model forms. But when I clicked submit, the image didn't get saved. It raises error 'this field is required'.

I've looked in some django docs also, but it has very concise material.

Upvotes: 2

Views: 1269

Answers (1)

Yaroslav Admin
Yaroslav Admin

Reputation: 14535

You need to add enctype="multipart/form-data" to your form tag, otherwise your file won't be uploaded to server. So update your form template to:

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" name="submit" value="create">
</form>

Upvotes: 5

Related Questions