Add rich text format functionality to django TextField
Asked Answered
B

2

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?

Breastfeed answered 20/11, 2013 at 12:24 Comment(0)
P
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

Pronator answered 31/10, 2017 at 9:42 Comment(1)
Here's the relevant section in the documentation: docs.djangoproject.com/en/dev/ref/templates/builtins/#safeLody
H
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

Hardee answered 24/3, 2019 at 16:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.