Home > database >  Django How to escape special character and use slice method in HTML template for json data
Django How to escape special character and use slice method in HTML template for json data

Time:01-25

before applying json method I was using this {{filt.body|striptags|safe|slice:":250" }} in my html template for escape all special character. Now my data loading from json and how to apply above method in my html template.

models.py

class Blog(models.Model):
       body = RichTextUploadingField()

views.py

class PostJsonListView(View):
    def get(self, *args, **kwargs):

        posts = list(Blog.objects.all().filter(is_published='published') )
        data = list()
        for i in posts:
            data.append({'body':i.body})
            
          
       
        return JsonResponse({'data':data},safe=False)

CodePudding user response:

You can do it in your view like this:

from django.utils.safestring import SafeString
from django.utils.html import strip_tags

for i in posts:
   body = strip_tags(SafeString(i.body))[:250]
   data.append({'body':  body})
  •  Tags:  
  • Related