Home > Software engineering >  Django HTML Create Buttons for Not Null Fields Only
Django HTML Create Buttons for Not Null Fields Only

Time:05-21

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?

CodePudding user response:

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 %}
  • Related