0

I project is supposed to be able to upload an image with a name then display the uploaded image and name. I have tried looking online for an answer to my problem but have found none. The problem basically is my django webapp is not saving a name(CharField)an and image(ImageField) to the database. I tried to do everything necessary for it to work but it's still not working. The following is my project. Thanks for your time.

My projectl directories: Image shows project structure

views.py

from django.shortcuts import render
from ImgApp.forms import ImageForm
from ImgApp.models import ImageModel
from django.http import HttpResponseRedirect


def upload(request):
    if request.method == "POST":
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('ImgApp:home')
    else:
        form = ImageForm()
        con = {"var_form": form}
    return render(request, 'upload.html', con)

models.py from django.db import models

class ImageModel(models.Model):
    name = models.CharField(max_length=44)
    image = models.ImageField(upload_to='media/',null=True)

    def __str__(self):
        return self.name

forms.py

from django import forms
from ImgApp.models import ImageModel

class ImageForm(forms.ModelForm):
    class Meta:
        model = ImageModel
        fields = "__all__"

settings.py

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'e3d)3&+&3!xkh_zz_l@uc9ly8uh@wio1g+zh59_mt&v-0xyubp'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'debug_toolbar',
    'ImgApp',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
]

ROOT_URLCONF = 'ImgProject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
            ],
        },
    },
]

WSGI_APPLICATION = 'ImgProject.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'

STATIC_DIR = os.path.join(BASE_DIR,'static')

STATICFILES_DIR = [
    os.path.join(BASE_DIR,'static')
]

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = "/media/"

INTERNAL_IPS = ['127.0.0.1']

urls.py

from django.conf.urls import url, include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from ImgApp import views


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^app/',include('ImgApp.urls')),
    url(r'^$',views.home),
    url(r'^upload/$',views.upload),
]

if settings.DEBUG:
    import debug_toolbar

    urlpatterns = [
                      url(r'^__debug__/', include(debug_toolbar.urls)),
                  ] + urlpatterns

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

upload.html

<form method="post" enctype="multipart/form-data" action="{% url 'ImgApp:index' %}">
        {% csrf_token %}
        {{var_form.as_p}}
        <input type="submit" value="upload" class="btn btn-primary">
    </form>

index.html

<!DOCTYPE html>
{% load static %}

........

{% if var_db %}
            {% for img in var_db %}
                <b>Name:</b>{{img.name}}
                <br>
                <img src="{{MEDIA_URL}}/{{img.image}}" alt="Image here" height="200" width="300">
            {% endfor %}
        {% else %}
            <p>No Images uploaded yet</p>
            <p>Fill this lonely area with happiness</p>
        {% endif %}
2
  • Check your MEDIA_ROOT folder. Are the files actually being created/saved? You need to fix how you're creating the src location. ImageField has a .url attribute that should do this for you; don't construct the path manually.
    – sytech
    Jan 17, 2018 at 1:53
  • The files are not being created. How exactly would I implement the .url in models? Jan 17, 2018 at 2:05

1 Answer 1

0

It looks as if you are posting the form to the index. You should post it to the upload view.

<form method="post" enctype="multipart/form-data" action="{% url 'ImgApp:upload' %}">

You need to add a name to the URL pattern for this to work.

url(r'^upload/$',views.upload, name='upload'),

In your view, you need to move the context line out of the else block so that it runs for GET and POST request. That means that if the form is invalid, you'll see the errors on the template.

def upload(request):
    if request.method == "POST":
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('ImgApp:home')
    else:
        form = ImageForm()
    context = {"form": form}
    return render(request, 'upload.html', context)

I've renamed a couple of variables to match the usual Django style (con to context, var_form to form). If you rename var_form, remember to update your template as well.

1
  • Ok that Works. Thank you so much again. I miss understood some things. Jan 17, 2018 at 22:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.