Add Css Class to urlize


I got this code for user info:

twitter   = models.CharField(max_length=255, blank=True, null=True) 
snapchat  = models.CharField(max_length=255, blank=True, null=True)
linkedin  = models.CharField(max_length=255, blank=True, null=True)

in Template i need to add CSS Class

class="fab fa-twitter icon"
class="fab fa-snapchat-ghost icon"

So i did this in template:

{% if user.twitter %}
 <a href="{{ user.twitter|urlize  }}" class="fab fa-twitter icon" target="_blank"></a>
{% endif %}

In this Code the class is out of the scope of the href.

Any idea how to add class to urlize.

What do you want the final anchor tag to look like when it’s rendered?

 <a href="" class="fab fa-twitter icon" target="_blank"></a>

Ok, the problem is that you are using urlize - you don’t need it in this situation. See Built-in template tags and filters | Django documentation | Django You might need to do some work with that twitter attribute, but otherwise, you’re rendering your own anchor tag.

without urlize tag

The link well be like:

Witch well led to 404 error.

What is the content of the twitter attribute?

this class:

class="fab fa-twitter icon"

No, the data in your model - what you’re accessing in the template as user.twitter. What does one sample instance of that attribute look like?

i want to go from this “User input”

to this in template:

 <a href="" class="fab fa-twitter icon" target="_blank"></a>

Yes, I understand that.

twitter = ""

And you render:
<a href="{{ twitter }}"> Link to twitter</a>

You will get:
<a href=""> Link to twitter</a>

What you posted as to what you think you would get would be an indication of a problem somewhere else.

Yes, The problem was somewhere else,
some user may input URL without HTTPS://
For that i use now URLField, that well force theme do insert a correct url format.

twitter   = models.URLField(max_length=255, blank=True, null=True) 
snapchat  = models.URLField(max_length=255, blank=True, null=True)
linkedin  = models.URLField(max_length=255, blank=True, null=True)

Thanks Ken :smiley: