Home > Blockchain >  Django ImageField not uploading on form submit but not generating any errors
Django ImageField not uploading on form submit but not generating any errors

Time:11-30

I have a simple app that uses an ImageField to upload & store a photo. I'm running the app local. The form displays as expected, and allows me to browse and select a jpg file. It then shows the selected filename next to the "Choose File" button as expected. When I submit the form, it saves the model fields 'name' and updates 'keywords' but it does not save the file or add the filename to the db. No errors are generated. Browsing the db, I see the newly added record, but the 'photo' column is empty. Any help appreciated.

settings.py:

MEDIA_ROOT = '/Users/charlesmays/dev/ents/ents/enrich/'

models.py:

class Enrichment(models.Model):
    name = models.CharField( max_length=255, unique=True)
    keywords = models.ManyToManyField(KeyWord, blank=True)
    photo = models.ImageField(upload_to='enrichments/', null=True, blank=True)

views.py:

def EnrichmentUploadView(request):
    if request.method == 'POST':
        form = CreateEnrichmentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('index'))
        else:
            return render(request, 'createEnrichment.html', {'form':form})

    else:
        form = CreateEnrichmentForm()
        return render(request, 'createEnrichment.html', {'form':form})

forms.py:

class CreateEnrichmentForm(forms.ModelForm):

    class Meta:
        model = Enrichment
        fields = ('name', 'photo', 'keywords')
        enctype="multipart/form-data"

template:

<form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save">
</form>

CodePudding user response:

Change all these, then it should work..

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    -------
]   static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

models.py

photo = models.ImageField(upload_to="enrichments/", default="")

And your template form

<form action="" id="" method="" enctype="multipart/form-data">
------
</form>
  • Related