0

I want to add an image for every post and I already tried setting the static link:

<img src="{% static {{ post.img }}">

I also tried uploading the img by writing in the models.py:

image = models.ImageField(upload_to=.....)

But it still does not work.

models.py

from django.db import models
from django.urls import reverse
from PIL import Image
# Create your models here.


class Post(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique=True)
    created = models.DateTimeField(auto_now_add=True)
    content = models.TextField(default="---")
    img = models.CharField(max_length=125, default='--')


    class Meta:
        ordering = ['-created']

        def __unicode__(self):
            return u'%s'% self.title

    def get_absolute_url(self):
        return reverse('Products.views.post', args=[self.slug])

Views.py

from django.shortcuts import render, render_to_response , get_object_or_404
from .models import Post


# Create your views here.
def index(request):
    posts=Post.objects.all()
    return render(request, 'Index.html', {"posts": posts})

def post(request, slug):
    return render(request, 'post.html', {'post': get_object_or_404(Post, slug=slug)})
1
  • Please add your model class in full to the question so we can see more code and help you troubleshoot. Commented Apr 24, 2018 at 16:54

2 Answers 2

1

The answer was that my settings.py wasn't configured correctly to display images so i had to add

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
Sign up to request clarification or add additional context in comments.

Comments

0

according to the things you've tried here a small summary:

The {% static %} template tag refferes to your static files, which means you should not use a variable in there to display the content. Mentioned here.

Except your Post model has a

img = models.CharField(...)

with the static file path to your image.

In your second attempt by adding a ImageField to your post model you should take the ImageFields property by calling {{ post.img.url }} as src of you img-Tag

6 Comments

It isn't working my html tag is <img src="{{ post.img.url }}" > my models.py img variable is img = models.ImageField(upload_to='temp', default=' ')
can you add your view to your question?
are you trying to render your image in your index, or post view?
in the index view
That's a bit different. Since you got a QueryDict of Posts you will need to iterate over them by using a for loop. Descriped in the Docs as well. (see this example) I really recommend you to read the template tags site, it's amazing what django offers you out of the box ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.