How to Create Buttons for not Null fields only in Django?

Question:

I’m fairly new to Django and couldn’t find a way to do this yet. I have a model like this:

class Profile(models.Model):
    user = models.OneToOneField("User", on_delete=models.SET_NULL, null=True)
    user_name = models.CharField(max_length=50)
    linkedin = models.URLField(max_length=254, null=True, blank=True)
    instagram = models.URLField(max_length=254, null=True, blank=True)
    spotify = models.URLField(max_length=254, null=True, blank=True)

On my HTML, I have buttons for each social media field, but I don’t want to show them if they are null. How can I create a for loop that will loop through the social media fields only and create buttons for only not null fields?

Asked By: matata

||

Answers:

If your links aren’t in a for loop in your HTML. I suggest you to use if block for every social media link.

example is:

{% if profile.linkedin %}
 <a href="{% url 'profile.linkedin' %}">LinkedIn</a>
{% if profile.spotify %}
 <a href="{% url 'profile.spotify' %}">Spotify</a>
{% else %}
{% endif %}
Answered By: enes islam
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.