无法使用文件字段在django中上传图像

Cannot upload image in django using filefield

我无法上传图片。

这是我的models.py

class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    image = models.FileField(upload_to = 'post/static/images/' , null= True, blank= True)
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

图片没有上传到 'post/static/images/'

这里是上传图片的模板

    {% if post.media %}
    <img src="{{ post.image.url }}" class="img-responsive" />
    {% endif %}

而且我觉得也是一件好事。

MEDIA_ROOT and STATIC_ROOT must have different values. Before STATIC_ROOT was introduced, it was common to rely or fallback on MEDIA_ROOT to also serve static files; however, since this can have serious security implications, there is a validation check to prevent it.

https://docs.djangoproject.com/en/1.11/ref/settings/#media-root

您想要做的(在开发中)是遵循本指南: https://docs.djangoproject.com/en/1.11/howto/static-files/#serving-files-uploaded-by-a-user-during-development

During development, you can serve user-uploaded media files from MEDIA_ROOT using the django.views.static.serve() view.

This is not suitable for production use! For some common deployment strategies, see Deploying static files.

For example, if your MEDIA_URL is defined as /media/, you can do this by adding the following snippet to your urls.py:

基本上,您将文件上传到 MEDIA_ROOT 中的某个位置,然后告诉 django 几乎将它们视为静态文件。但是你不直接上传到静态。

你的代码有很多问题:

  1. 在您的模型中 - 使用字段进行图片上传 ImageField(要使用 ImageField,您需要安装 Pillow):

    image = models.ImageField(upload_to = 'images/' , null= True, blank= True)
    

    (您将上传图像到名为 images 的 MEDIA_ROOT 文件夹的子文件夹中)

  2. 同时将图像放在媒体文件夹中 - 您必须创建一个,在 settings.py 文件夹中添加:

    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
    
  3. 为了让 django 为您的媒体服务(仅用于开发!)您必须在您的 main 中添加(从您的项目目录而不是您的应用程序文件夹)urls.py 文件:

    from django.conf import settings
    from django.conf.urls.static import static
    
    if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
  4. 上传图片的简单表单示例:

    <form action="{% url upload_pic %}" method="post" enctype="multipart/form-data">{% csrf_token %}
        <input id="id_image" type="file" class="" name="image">
        <input type="submit" value="Submit" />
    </form>
    

    其中 url_upload_pic 是应该处理图像上传的(功能)视图。