django勉強中のものです。  
今、画像投稿の機能をつけようとして、adminページからは登録できるようになったのですが、普通のフォームから投稿しようとすると、できない状態です。  
具体的には、下記のようなフォームで画像選択はできるのですが、送信を押してしまうと、画像が選択されていませんと出てしまいます。

[![入力段階では選択されていますが](https://i.stack.imgur.com/iIVLh.png)](https://i.stack.imgur.com/iIVLh.png)  
[![送信を押すと保存されていません。実際ディレクトリにも保存されていません。](https://i.stack.imgur.com/Akjca.png)](https://i.stack.imgur.com/Akjca.png)

環境  
dockerで構築  
python3.7.3  
django2.1.1  
pillow:pipでインストール済み

コードは以下のとおりです。

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__)))
    
    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.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/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})
    
    
    def edit_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')
    
    
    
```

入力フォームのhtml

```

    <div>
      <a href="{% url 'E_journal:index' %}">ホームに戻る</a>
    </div>
    
    <form action="{% url 'E_journal:new_journal' %}" method="POST">{% csrf_token %}
      {{ form.as_p }}
      <button type="submit" class="btn">保存</button>
    </form>
    
```

以上が主なコードです。  
回答お願いします。
CC BY-SA 4.0
2019-05-05T10:10:18.507
54741
2019-05-05T14:17:17.980
2019-05-05T14:17:17.980
3068
34191
question
django
django2.1.1で画像投稿がうまくできない。
自己解決しました。  
formタグの１つ目の要素にenctype="multipart/form-data"をつけたら行けました。  
ちなみに、2つ目以降につけるとだめだったので、Ⅰつめじゃないと行けないようです。
CC BY-SA 4.0
2019-05-05T12:22:12.397
54747
2019-05-05T12:22:12.397
34191
54741
answer