Home > Enterprise >  Django need first paragraph
Django need first paragraph

Time:10-19

I created model with my posts. file blog/models.py:

import datetime

from ckeditor.fields import RichTextField
from django.db import models


class Post(models.Model):
    name = models.CharField(max_length=250)
    content = RichTextField()
    date = models.DateField(default=datetime.date.today)

and in db i has this record:

<p>First paragraph</p>

<p>Second paragraph</p>

<p>Third paragraph</p>

<p>etc</p>

<p>...</p>

How I can get result First paragraph ONLY

CodePudding user response:

You could work with BeautifulSoup and make a property that will return the HTML content of the first paragraph. You first install beautifulsoup with:

pip3 install beautifulsoup4

then we can define a property that implements logic to extract the first <p> tag:

from bs4 import BeautifulSoup

class Post(models.Model):
    name = models.CharField(max_length=250)
    content = RichTextField()
    date = models.DateField(auto_now_add=True)

    def first_paragraph(self):
        bs = BeautifulSoup(self.content)
        return str(bs.find('p'))
  • Related