how to remove html tags in django template on browser while showing to user - django

As shown in figure i used {{options|safe}} for rendering options in my django 3.0 polls application even though it is rendering like that and i don't know how to remove the tags from rendered string, thanks for help in advance
regarding tag error

To remove tags, I would recommend using Mozilla's bleach library.
In order to remove tags only in the front-end, not the data itself, you can easily create a custom template filter and clean the tags inside it.
Another cool idea would be to have list of enabled HTML tags that can be used (like making text bold with <b>...</b>) and then render the input as a valid html:
{{ options|remove_tags|safe }}
Example for a custom template filter:
#register.filter
def remove_tags(value):
return bleach.clean(value, tags=["b", "i"])

Related

Django: a custom template tag to convert links inside of a TextField and change the hyperlink text

The scenario is that there are some dynamic texts on some templates, that will contain hyperlinks.
For this, I have a SiteDataKeyValue model, in which the dynamic texts for different parts of the template are inputted. This is the model:
class SiteDataKeyValue(models.Model):
key = models.CharField(
max_length=200, verbose_name="نام متن مورد نظر", unique=True
)
value = models.TextField(verbose_name="متن")
def __str__(self):
return self.key
A solution that I've found already, is Django urlize template tag. As mentioned in the docs, this tag converts texts like https://www.google.com to www.google.com, which is nice but not what I'd like to achieve. I want to be able to change the hyperlink text, so the output would be something like: Click Here!.
I searched for a bit, came across modules like bleach, which is a fine module, but I couldn't find the answer I was looking for (I skimmed through the docs and there was nothing about the hyperlink text).
Also I saw a comment somewhere telling that this could be achieved by writing a custom Django template tag, but although I tried to do this regarding the custom template filters docs, I didn't have a clue to how to achieve this.
I'm not asking for the code, although it would be really appreciated if you provide instructions for writing this custom template tag, or better, if you could point me to something like this that is already out there.
First of all you can extend urlize tag like the answer in this
or you can change the main code which you can find it in django.utils.html and override its url variable to change it.
But I think the best method is extending the urlize tag
like this:
{% text | urlize | change_a_text_filter:{{ dome_new_a_text }} %}
then you can scrape the text and use regex to find >sample-text</a> then you can change it to the argument that defines in your tag
from django import template
register = template.Library()
#register.simple_tag
def change_a_text_filter(format_string, arg):
# find the url that made in urlize with regex
# change it with arg
# return the result
I was on a completely wrong road to solve this problem. I was trying to urlize a link from TextField, but didn't consider the fact that I only needed to implement html code as Visit link.com! in the TextField, and then use safe template tag to render html directly as below:
{{ text.value|safe }}
So in this solution, there is no need to urlize, and of course there is no need to extend this tag neither.
NOTE: As commented by #rahimz (link to comment) I understand that there are safety concerns regarding safe tag, So I should emphasize that only me and a company-trusted admin will have access to admin panel and there is no worries that this admin will send malicious code through this TextField.

Can we enter html code in a field in models in django?

I am making a small static website in which I have a template in which I tend to show the privacy policy terms of usage etc. I currently don't have any matter for it and tend to add it in future after deploying the site on server. I wanted to know that if I can in future add the matter on that page through a model i.e I create a model with two fields privacy policy , terms and in and pass it to the template as context in views.py . But I have a concern that the fields will have several headings which I will have to display in bold , so is there any way that I can pass html tags in model field and when I render it in my template as {{privacy}} the part I want in bold or any other style comes as that style.
So is there any way that I can pass html tags in model field and when I render it in my template as {{privacy}} the part I want in bold or any other style comes as that style.
Yes. You only need to tell the Django template engine not to escape the characters (for example translate < to <). You can do this with the |safe template tag [Django-doc]:
{{ privacy|safe }}

Detect URLs and #tags in Django CharField and add style to it

For now on I have in my template a paragraph like this <p class="...">{{ post.content }}</p> and if this Post's content contains a link or #hashtag it is rendered as a normal text with the rest of the post. How can I customize it? For example change text-color and add tag around it?
As I said in comment, you can use custom tag filter to wrap your content, and use Regular Expression to generate links and hashtags
Create your tags file, and name it as you want:
tag_filter_name.py
If you're not familiar with custom tag filter creation, you can learn more about it in the Official Documentation
from django import template
import re
register = template.Library()
def generate_link(link):
return '<a class="link" href="{}">{}</a>'.format(link, link)
def generate_hashtag_link(tag):
# Free to configuree the URL the way adapted your project
url = "/tags/{}/".format(tag)
return '<a class="hashtag" href="{}">#{}</a>'.format(url, tag)
And then, you create the function what will be used as tag filter
#register.filter
def render_content(obj):
text = re.sub(r"#(\w+)", lambda m: generate_hashtag_link(m.group(1)),obj)
return re.sub(r"(?P<url>https?://[^\s]+)", lambda m: generate_link(m.group(1)),text)
If you want Django to mark it as safe content, you can do the following:
from django.utils.safestring import mark_safe # import function
''' function codes here '''
return mark_safe(re.sub(r"(?Phttps?://[^\s]+)",
lambda m: generate_link(m.group(1)),text))
And finally, to use it in your template, don't forget to load it
{% load tag_filter_name %}
{{ post.content|render_content }}
Best way: custom tag filters here is the docs URL
https://docs.djangoproject.com/en/2.2/ref/templates/builtins/
Good way: If you know JS create a function that handles the formatting on the front end
in HTML:
onload="myfunction("{{post.content}}")"
in JS sort for the string containing the # wrap it in a span or other element and style away. then replace the inner HTML with your new formatted piece. This will save rendering time on the server and also frees you up from having to loop thru the list of posts in the view
Ok way: not preferred but if you hate js and only want to work in python (understandable). You need to loop through the list of posts separate out the items of the post format them the way you like with inline style. then add them to a new object that you will append to the end of a new list of posts that you will then pass thru to context. This is a real pain please don't do this if you can help it at all.
the tag filters are awsome take advantage but if they won't work for your use case I would highly advise using vanilla JS

Setting html-attributes to HTML forms using serializer in Django

I want to make page with form that contains any kinds of inputs. I'm using Django and rest framework. I've succeded in representing HTML form using rest framework {% render_form %} tag and serializer with some fields. But i'm just able to set few attributes, for instance, placeholder and input_type. And it works well. The next thing I want is setting some #id, .class and any attributes to input tags(or select) on a server side because I need to handle these HTML forms using knockoutjs or JQuery but I can't do it without data-bindings or #IDs. I couldn't find any information about it. I guess it is possible to set any attributes to inputs on client-side finding them by label name but it seems a bad way. Or maybe I could get list of fields and just represent it in html template? Are there some pieces of advice?

WYSIWYG editor pastes html tags in output textfield

I use this redactor for admin site django-wysiwyg-redactor
But when I enter some text, it pastes it with html tags. When discovering my source code, I noticed that html code that is responsible for my input data, is placed in quotes.
I think you have to use "safe", the built-in template filter to render the html properly in your template. Example:
{{ myTextField|safe }}
Safe in django docs