Image will not upload from a form in django. Image will upload if entered from admin panel but not from form

Viewed 21

the image will not upload if done thru the form. if the image is uploaded thru the admin interface it works properly.. after several hours of researching the docs and google I cannot figure out whats wrong if anyone has any clue I would be greatly appreciative

model

class Event(models.Model):
    TYPE = [
        ('CYCLING','cycling'),
        ('STAIR CLIMB','stair climb'),
        ('RUNNING','running'),
    ]
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False
    )
    event_name = models.CharField('Event Name', max_length=100)
    event_location = models.CharField('Event Location', max_length=100)
    event_date = models.DateField('Event Date')
    event_description = models.TextField('Event Description')
    event_type = models.CharField('Event Type', max_length=30, choices=TYPE, default='CYCLING')
    event_img = models.ImageField( upload_to="eventImg/", blank=True, null=True )
    def __str__(self):
        return self.event_name


    def get_absolute_url(self):
        return reverse('event-detail',args=[str(self.id)])

form.py

class AddEventForm(forms.ModelForm):
        class Meta:
            model = Event
            fields = ('event_name','event_date','event_location','event_type','event_description','event_img')

template

{% extends '_base.html' %}
{% load materializecss %}
{% block title %} Add  Event{% endblock title %}

{% block content %}

<div class="container" >
    <h1>Add Event </h1><i class = 'material-icons large'>pedal_bike</i><i class = 'material-icons large blue-text'>directions_walking</i><i class = 'material-icons small green-text'>
    directions_running</i>
</i>
    <form method = 'POST' enctype="multipart/form-data">
        {% csrf_token %}
        {{form|materializecss}}
        <button type = 'submit' class = 'btn waves-effect waves-light amber lighten-2 black-text hoverable'>Add Event
            <i class = 'material-icons right'>send</i></button>
    </form>
</div>
{% endblock content %}

urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
    # Knight Ryders Admin
    path('admin/', admin.site.urls),

    #    User Management
    path('accounts/', include('allauth.urls')),
    path('accounts/', include('django.contrib.auth.urls')),

    # local apps
    path('', include('knightryders_app.urls')),

]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I have edited this question and added the views.py file for the form again any help is appreciated

def add_event(request):
    submitted = False
    if request.method == 'POST':
        form = AddEventForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/Event/List/')
    else:
        form = AddEventForm()
        if 'submitted' in request.GET:
            submitted = True

    return render(request,'add-event.html', {'form':form, 'submitted':submitted })
2 Answers

You need to pass the request.FILES to the form as well, request.POST only contains the items filled in in the form, but not the files uploaded:

def add_event(request):
    submitted = False
    if request.method == 'POST':
        form = AddEventForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/Event/List/')
    else:
        form = AddEventForm()
        submitted = 'submitted' in request.GET

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

request.POST just contain texting fields not images or files you need also pass request.FILES for getting file or image.

def add_event(request):
    submitted = False
    if request.method == 'POST':
        form = AddEventForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/Event/List/')
    else:
        form = AddEventForm()
        if 'submitted' in request.GET:
            submitted = True

    return render(request,'add-event.html', {'form':form, 
'submitted':submitted })
Related