How to save links to TextFields
I have a simple blog model with TextField. What's the best way to store links in a TextField?
1) Saving the link in the database in this form: http://www.example.com and then using some filter in the template to convert it to the form:
<a rel="nofollow" href="http://www.example.com>http://www.example.com</a>
2) Saving the link in the database directly in this form:
<a rel="nofollow" href="http://www.example.com>http://www.example.com</a>
a source to share
Assuming you are talking about how to preserve links (or any HTML formatting really) that you include in your blog posts, rather than individual links (for a blogroll, for example):
You might want to consider using some kind of markup language like Markdown or BBCode. Then you save the blog post in pure markup syntax and provide a method (for example blog.get_post()
) that will parse the saved markup and return HTML. Then you used a filter safe
in your template to avoid HTML escaping.
Better yet, to avoid parsing the markup on a per request basis, cache it in the database. Add a TextField called text_html to your model Blog
. Override the Blog
model method save
to parse the markup in HTML and store the HTML in the text_html field.
Then when you want to display a blog post in a template, you can use it {{ post.text_html|safe }}
without having to parse your markup every time.
So your blog model might look like this (textbox only).
import markdown
class BlogPost(models.Model):
text = models.TextField()
text_html = models.TextField(editable=False) # don't want to see this in Admin
def save(self, force_insert=False, force_update=False):
self.text_html = markdown(self.text)
super(BlogPost, self).save(force_insert, force_update)
To make things easier on the data input side, you can also add a nice javascript editor to it - like the one I'm typing this answer right now .
a source to share
I would save the url itself and add the tag and parameters in the output. In my opinion, it is better to separate storage, processing and presentation of data, to facilitate future changes (for example, when in a future version the URL will be used for something completely different, such as automatic loading).
a source to share