SilentDev
SilentDev

Reputation: 22747

Django - take users form input and create a link in a certain part of the input?

This is my models.py:

class Post(models.Model):
    actualPost = models.CharField(max_length=200)

And this is my forms.py:

class PostForm(forms.ModelForm):
    class Meta:
    model = Post
    fields = ['actualPost']
    widgets = { 'actualPost' : forms.Textarea(attrs={'maxlength':200}) }

This is my views.py:

def createPostView(request):
    if request.method=='POST':
    form = PostForm(request.POST)
    if form.is_valid():
            stringPost = form.cleaned_data['actualPost'] #I'm assuming stringPost will now be the string version of the users input
            findLinks(stringPost)
            newPost = Post(actualPost = form.cleaned_data['actualPost'])

So basically in the view, after getting the string version of the users input / post, I plan on sending that string to a function called findLinks. This is the findLinks function:

def findLinks(postString):
    word = ''
    totalLength = len(postString)
    for i in postString:
        if i=='@': #basically, I want anything after an '@' sign to be a link.. 
                   #so if the post is "Go to @www.google.com to search for anything"
                   #I want www.google.com to be a link 
            indexOfSign = postString.index(i)
            while ((indexOfSign != totalLength-1) and (postString[indexOfSign+1] != '')):
                 word += htmlString[indexOfSign+1]
                 indexOfSign += 1
    return word

The function does return the word after the '@' sign. So now that it returns the word after the @ sign, how I do safely make that word a link so that when I put the post in a template, then when I view the template, the word after the @ sign will appear as a link?

One possible way I was thinking was, in the python function, basically return the string version of the post except with the word after the @ sign wrapped around with "" and "", but this will not work because for safety reasons, Django interprets user input as a raw string rather than code, correct?

I don't want to force Django to interpret Post's as code rather than raw string because that will cause security issues. Is there any way for me to safely take the users input and save it to the database and in the template, make all words which come after the '@' sign a link?

Upvotes: 0

Views: 977

Answers (1)

karthikr
karthikr

Reputation: 99620

Declare a class method like this:

class Post(models.Model):
    actualPost = models.CharField(max_length=200)

    def get_link(self):
        if self.actualPost and '@' in self.actualPost:
            return self.actualPost.split('@', 1)[1]
        return None

and in the template

{% for post in post_list %}
    {% if post.get_link %}
        <a href="/{{ post.get_link }}/">Blah </a>
    {% endif %}
{% endfor %}

Upvotes: 1

Related Questions