Get the first image src from a post in django -
i have model write blogs. in i'm using wysiwyg editor blog's descritpion, through can insert image within description.
class blog(models.model): title = models.charfield(max_length=150, blank=true) description = models.textfield() pubdate = models.datetimefield(default=timezone.now) publish = models.booleanfield(default=false) in admin looks this:

what want first image inside description of blog, , present in template this:

how img src description of blog use in template? , guidance appreciated. thank you.
views.py:
def blog(request): blogs = blog.objects.all() return render(request, 'blogs.html', { 'blogs':blogs }) template:
{% blog in blogs %} <div class="blog"> <p class="blog_date"> {{blog.pubdate}} </p> <h2 class="blog_title"> {{blog.title}} </h2> <img src="{{static_url}} ###img src included" class="blog_image img-responsive img-thumbnail"> <a href="blog_detail.html" class="blog_read_more btn btn-info">read more</a> <div class="container"> <p class="divider">***</p> </div> </div> {% endfor %}
here's basic approach can tweak convenience:
add first_image field model:
class blog(models.model): title = models.charfield(max_length=150, blank=true) description = models.textfield() pubdate = models.datetimefield(default=timezone.now) publish = models.booleanfield(default=false) first_image = models.charfield(max_length=400, blank=true) now have populate first_image field on save, model's save method should this:
def save(self, *args, **kwargs): # regex grab first img url # note have use double quotes src attribute img = re.search('src="([^"]+)"'[4:], self.description) self.first_image = img.group().strip('"') super(blog, self).save(*args, **kwargs) now reference in template.
this not fledged solution, there other things should take account, differentiating between smiley or thumbnail or code snippet imr src , actual img src, should personal use, don't want limit other people's choice having first image cover image.
hope helps!
Comments
Post a Comment