Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add rich text format functionality to django TextField

Tags:

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?

like image 206
Shiva Krishna Bavandla Avatar asked Nov 20 '13 12:11

Shiva Krishna Bavandla


2 Answers

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

like image 109
David Avatar answered Oct 06 '22 11:10

David


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

like image 43
marqpdx Avatar answered Oct 06 '22 09:10

marqpdx