I can't post images well in django 2.1.1.

Asked 2 years ago, Updated 2 years ago, 57 views

I'm studying django.
Now, I'm trying to add a function for posting images, and now I can register from the admin page, but when I try to post from a normal form, I can't.
Specifically, you can select an image using the form below, but if you press Send, it will appear if the image is not selected.

It was selected at the input stage, but
Press Send to save.It is not even stored in the actual directory.

Environment
Build with docker
python 3.7.3
django 2.1.1
pillow:pip installed

The code is as follows:

settings.py

importos

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

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

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY='$tq17%7y8+#&n9m^zn_dfiewt5t@hx=qk3sa3fvzs7kh%#^paq'

# 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',
    'e_journal',
    'stdimage',
]

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',
]

ROOT_URLCONF = 'journal.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        DIRS: [ ],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'journal.wsgi.application'


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

DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.postgresql',
    'NAME': 'postgres',
    USER: 'postgres',
    'HOST': 'db',
    'PORT': 5432,
  }
}

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

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilityValidator',
    },
    {
        '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/2.1/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/2.1/howto/static-files/

STATIC_URL='/static/'

urls.py

"journal URL Configuration

The `urlpatterns`list routes URLs to views.For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import: from my_app import views
    2. Add a URL to urlpatterns: path(', views.home, name='home')
Class-based views
    1. Add an import: from other_app.views import Home
    2. Add a URL to urlpatterns: path(', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from.import settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('admin/', admin.site.urls),
    path(', include('e_journal.urls')
]

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

forms.py

 from django.forms import ModelForm
from.models import E_journal

class journal_form (ModelForm):
    class Meta:
        model=E_journal
        fields = ['title', 'text', 'photo']


models.py

 from django.db import models

class E_journal (models.Model):
    title=models.CharField(blank=False, null=False, max_length=150)
    text=models.TextField(blank=True)
    photo=models.ImageField(upload_to='documents/')
    created_datetime=models.DateTimeField(auto_now_add=True)
    updated_datetime=models.DateTimeField(auto_now=True)

    def__str__(self):
        return self.title

views.py

 from django.shortcuts import render, redirect
from.models import E_journal
from.forms import journal_form
from django.views.decorators.http import require_POST  

def index(request):
    content=E_journal.objects.order_by('-created_datetime')
    return render(request, 'e_journal/index.html', {'content':content})


def detail(request, content_id):
    content=E_journal.objects.get(id=content_id)
    return render(request, 'e_journal/detail.html', {'content':content})


def new_journal(request):
    if request.method == 'POST':
        form = journal_form(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('E_journal:index')
    else:
        form = journal_form()
    return render(request, 'e_journal/new_journal.html', {'form':form})


default_journal(request, content_id):
    content=E_journal.objects.get(id=content_id)
    form=journal_form(instance=content)
    return render(request, 'e_journal/edit_journal.html', {'form':form, 'content':content})

@require_POST
def delete_journal(request, content_id):
    content=E_journal.objects.get(id=content_id)
    content.delete()
    return redirect('E_journal:index')


Input Form html

<div>
  <a href="{%url'E_journal:index'%}">Return to Home </a>
</div>

<form action="{%url'E_journal:new_journal'%}" method="POST">{%csrf_token%}
  {{ form.as_p}}
  <button type="submit" class="btn">Save</button>
</form>

These are the main codes.
Please reply.

django

2022-09-29 22:00

1 Answers

I solved myself.
The first element of the form tag was enctype="multipart/form-data" and I could go.
By the way, I couldn't wear it after the second one, so I have to wear the first one.


2022-09-29 22:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.