pythondjangodjango-modelsdjango-uploads

Cannot upload image in django using filefield


I am not able to upload image.

here is my 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

the image is not getting uploaded to 'post/static/images/'

here is the template for uploading the image

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

Solution

  • There are many problems with your code:

    1. In your model - use the field for image uplaoding ImageField (to use ImageField you need to have installed Pillow):

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

      (you will upload the images in a subfolder of the MEDIA_ROOT folder named images)

    2. Also put the images in the media folder - you have to create one, in the settings.py folder add:

      MEDIA_URL = '/media/'
      MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
      
    3. To let django serve your media (only for development!) you have to add in your main (from your project directory not from your app folder) urls.py file:

      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. An example of a simple form to upload an image:

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

      where url_upload_pic is the (function) view which should handle the upload of the image.