Answer the question
In order to leave comments, you need to log in
How to add images to articles in Django?
Hello.
When I add an article to the site via the django admin, I also need to add an image to it. How to do it? And how to make it appear on the page with the article. As far as I know, ImageField is used for this, but it's not so simple there.
Could you give an example of how to implement this or throw off a link to the lesson?
I understand that now many will recommend that I search on Google, but still I did not find a complete instruction there, everywhere it is only explained in parts.
Thanks in advance!
Answer the question
In order to leave comments, you need to log in
If you use only one image
- add a field for the image to the model
- add an image placeholder to the template
# models.py
class Article(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
img = models.ImageField(upload_to='/article',
height_field=100, width_field=100)
#urls.py
url(r'^article/(?P<pk>[0-9]+)/$', DetailView.as_view(
context_object_name="article",
model=Article,
template_name="article.html"
), name='article-detail'),
#article.html
<h1>{{ article.title }}
<img src="{{ article.img.url }}">
<content>{{ article.context }}
django-ckeditor
If ImageField is needed:
class YourModel(Model):
# ...
image = ImageField(upload_to='images/', null=True, blank=True)
def generate_path(instance, filename):
ext = filename.rsplit('.', 1)[-1]
h = md5(instance.user.username.encode()).hexdigest()
result = 'photos/%s/%s/%s.%s' % (h[:2], h[2:4], h[4:], ext)
path = os.path.join(settings.MEDIA_ROOT, result)
if os.path.exists(path):
os.remove(path)
return result
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question