无法使用django将图像保存到数据库

时间:2018-01-17 01:49:01

标签: python django django-models

我的项目应该能够上传带有名称的图像,然后显示上传的图像和名称。我试过在线寻找我的问题的答案,但没有找到。问题基本上是我的django webapp没有将名称(CharField)和图像(ImageField)保存到数据库中。我试图做一切必要的工作,但它仍然无法正常工作。以下是我的项目。谢谢你的时间。

我的projectl目录: 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 来自django.db导入模型

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 %}

1 个答案:

答案 0 :(得分:0)

看起来好像是要将表单发布到索引中。您应该将其发布到<script type="text/javascript"> window.addEventListener('hashchange', function(){ document.querySelector('.active').classList.remove('active'); document.querySelector('[href="'+window.location.hash+'"]').classList.add('active'); }); </script> 视图。

upload

您需要为URL模式添加一个名称才能使其生效。

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

在您的视图中,您需要将上下文行移出url(r'^upload/$',views.upload, name='upload'), 块,以便它为GET和POST请求运行。这意味着如果表单无效,您将在模板上看到错误。

else

我已经重命名了几个变量来匹配通常的Django样式(con到context,var_form形成)。如果您重命名var_form,请记住也要更新模板。