21

I have a django model which contains a description field:

class Product(models.Model):
    name = models.CharField(max_length="125")
    description = models.TextField()

class ProductForm(ModelForm):
    class Meta:
        model = Product
    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)
        self.fields['description'].widget.attrs = { 'placeholder':'Description', 'rows':'10'}

I am rendering it as below

<html>
  <body>
     {{form.name}}
     {{form.description | linebreaks}}  
  </body>
</html>

So with the above filter linebreaks I am able to get the data as line formatting, but now I want to give a url(www.google.co.in) in the description field, and it should be a clickable on the front end in the product detail page

How to add the rich text formatting to django description field on front end?

Mel
  • 5,837
  • 10
  • 37
  • 42
Shiva Krishna Bavandla
  • 25,548
  • 75
  • 193
  • 313

2 Answers2

8

Another way could be adding some html in the description field

<a href="yourlink.com">your link</a> 

and make it accessible on the front-end with the safe tag:

{{form.description | safe | linebreaks}}

Be sure of placing the safe tag first, otherwise won't work

David
  • 119
  • 1
  • 5
  • Here's the relevant section in the documentation: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#safe – natka_m Jun 22 '20 at 16:43
3

Late to the party i know, but another option i've been using is using the Wagtail admin, and specifically from wagtail.core.fields import RichTextField. This gives the admin a built-in and very nice Rich Text editor.

You can create basic django models and use the RichTextField as part of the model, and then you can register that model with Wagtail and you get a very nice editing interface with built-in WYSWIG. You can see more here: https://docs.wagtail.io/en/v2.4/reference/contrib/modeladmin/index.html

marqpdx
  • 51
  • 1
  • 4