Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python django ImageField上载的问题_Python_Django - Fatal编程技术网

Python django ImageField上载的问题

Python django ImageField上载的问题,python,django,Python,Django,我的问题是我只能从管理面板上传图片。每当我尝试上传时,通过我制作的表单,图像似乎没有保存 型号.py from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible import uuid from django.db import models from django.conf import settings

我的问题是我只能从管理面板上传图片。每当我尝试上传时,通过我制作的表单,图像似乎没有保存

型号.py

    from __future__ import unicode_literals
    from django.utils.encoding import python_2_unicode_compatible
    import uuid
    from django.db import models
    from django.conf import settings
    from django.core.urlresolvers import reverse

    import os
    import uuid

    YESNO_CHOICES = (
        (0, 'Ja'),
        (1, 'Nej')
        )


    SESSION_CHOICES = (
        (0, '1'),
        (1, '2'),
        (2, '3'),
        (3, '4'),
        (4, '5'),
        )

    def upload_to_location(instance, filename):
        blocks = filename.split('.')
        ext = blocks[-1]
        filename = "%s.%s" % (uuid.uuid4(), ext)
        instance.title = blocks[0]
        return os.path.join('uploads/', filename)
    # Create your models here.

    class Client(models.Model):
        fulde_navn = models.CharField('Navn', max_length=75)
        adresse = models.CharField(max_length=100)
        email = models.EmailField(null=True, blank=True)
        tidligere_klient = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True)
        foerste_session = models.DateField('Dato for 1. session', null=True, blank=True)
        beskrivelse = models.TextField('Noter', null=True, blank=True)
        arbejde = models.CharField('Arbejde', max_length=200)
        relateret_til_andre_klienter = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True)
        vurder_sidste_session = models.IntegerField(choices=SESSION_CHOICES, null=True, blank=True)
        profilbillede = models.ImageField('Profilbillede',
                                    upload_to='profile_pics/%Y-%m-%d/',
                                    null=True,
                                    blank=True)


        def __unicode__(self):
            return self.fulde_navn

        def get_absolute_url(self):
            return reverse(viewname="client_detail", args=[self.id])
from django import forms

from .models import Client

class ClientForm(forms.ModelForm):


    class Meta:
        model = Client
        fields = (
            'fulde_navn',
            'adresse',
            'email',
            'tidligere_klient',
            'foerste_session',
            'beskrivelse',
            'arbejde',
            'relateret_til_andre_klienter',
            'vurder_sidste_session',
            'profilbillede'
        )
这里是forms.py

    from __future__ import unicode_literals
    from django.utils.encoding import python_2_unicode_compatible
    import uuid
    from django.db import models
    from django.conf import settings
    from django.core.urlresolvers import reverse

    import os
    import uuid

    YESNO_CHOICES = (
        (0, 'Ja'),
        (1, 'Nej')
        )


    SESSION_CHOICES = (
        (0, '1'),
        (1, '2'),
        (2, '3'),
        (3, '4'),
        (4, '5'),
        )

    def upload_to_location(instance, filename):
        blocks = filename.split('.')
        ext = blocks[-1]
        filename = "%s.%s" % (uuid.uuid4(), ext)
        instance.title = blocks[0]
        return os.path.join('uploads/', filename)
    # Create your models here.

    class Client(models.Model):
        fulde_navn = models.CharField('Navn', max_length=75)
        adresse = models.CharField(max_length=100)
        email = models.EmailField(null=True, blank=True)
        tidligere_klient = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True)
        foerste_session = models.DateField('Dato for 1. session', null=True, blank=True)
        beskrivelse = models.TextField('Noter', null=True, blank=True)
        arbejde = models.CharField('Arbejde', max_length=200)
        relateret_til_andre_klienter = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True)
        vurder_sidste_session = models.IntegerField(choices=SESSION_CHOICES, null=True, blank=True)
        profilbillede = models.ImageField('Profilbillede',
                                    upload_to='profile_pics/%Y-%m-%d/',
                                    null=True,
                                    blank=True)


        def __unicode__(self):
            return self.fulde_navn

        def get_absolute_url(self):
            return reverse(viewname="client_detail", args=[self.id])
from django import forms

from .models import Client

class ClientForm(forms.ModelForm):


    class Meta:
        model = Client
        fields = (
            'fulde_navn',
            'adresse',
            'email',
            'tidligere_klient',
            'foerste_session',
            'beskrivelse',
            'arbejde',
            'relateret_til_andre_klienter',
            'vurder_sidste_session',
            'profilbillede'
        )
最后,我的设置.py应该是相关的:

# Build paths inside the project like this: join(BASE_DIR, "directory")
BASE_DIR = dirname(dirname(dirname(__file__)))
STATICFILES_DIRS = [join(BASE_DIR, 'static')]
MEDIA_ROOT = join(BASE_DIR, 'media')
MEDIA_URL = "/media/"

# Use Django templates using the new Django 1.8 TEMPLATES settings
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            join(BASE_DIR, 'templates'),
            # insert more TEMPLATE_DIRS here
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
                # list if you haven't customized them:
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.template.context_processors.request',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# Use 12factor inspired environment variables or from a file
import environ
env = environ.Env()

# Ideally move env file should be outside the git repo
# i.e. BASE_DIR.parent.parent
env_file = join(dirname(__file__), 'local.env')
if exists(env_file):
    environ.Env.read_env(str(env_file))

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

# SECURITY WARNING: keep the secret key used in production secret!
# Raises ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = 'uvtzrap(uor-n!_*9qtw!m^m9vh29tuggst=^mvmb_omp08+qo'

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.auth',
    'django_admin_bootstrapped',
    'django.contrib.admin',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'authtools',
    'crispy_forms',
    'easy_thumbnails',
    'geoposition',
    'bootstrap_pagination',

    'profiles',
    'accounts',
    'clients',

)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'saas.urls'

WSGI_APPLICATION = 'saas.wsgi.application'

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

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

# Internationalization
# https://docs.djangoproject.com/en/dev/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/dev/howto/static-files/

STATIC_URL = '/static/'

ALLOWED_HOSTS = []

# Crispy Form Theme - Bootstrap 3
CRISPY_TEMPLATE_PACK = 'bootstrap3'

# For Bootstrap 3, change error alert to 'danger'
from django.contrib import messages
MESSAGE_TAGS = {
    messages.ERROR: 'danger'
}

# Authentication Settings
AUTH_USER_MODEL = 'authtools.User'
LOGIN_REDIRECT_URL = reverse_lazy("profiles:show_self")
LOGIN_URL = reverse_lazy("accounts:login")

THUMBNAIL_EXTENSION = 'png'     # Or any extn for your thumbnails

免责声明:我知道这不是最吸引人的代码,但我是编程新手。对不起

根据您的代码,您编写了一个函数,用于为上载的文件生成新名称,但您没有使用它更改

profilbillede = models.ImageField('Profilbillede',
                                    upload_to='profile_pics/%Y-%m-%d/',
                                    null=True,
                                    blank=True)
profilbillede = models.ImageField('Profilbillede',
                                    upload_to=upload_to_location,
                                    null=True,
                                    blank=True)

profilbillede = models.ImageField('Profilbillede',
                                    upload_to='profile_pics/%Y-%m-%d/',
                                    null=True,
                                    blank=True)
profilbillede = models.ImageField('Profilbillede',
                                    upload_to=upload_to_location,
                                    null=True,
                                    blank=True)

应该解决问题

您应该在此处提供尽可能多的代码详细信息,以缩小问题范围,以便人们能够更好地帮助您。你不能仅仅给出回购协议,让人们直观地搜索你做错了什么。是的,你是对的。我会改变的