【问题标题】:How to Create Buttons for not Null fields only in Django?如何仅在 Django 中为非 Null 字段创建按钮?
【发布时间】:2022-08-14 14:18:29
【问题描述】:

我对 Django 还很陌生,还没有找到方法来做到这一点。我有一个这样的模型:

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)

在我的 HTML 中,每个社交媒体字段都有按钮,但如果它们为空,我不想显示它们。如何创建一个仅循环遍历社交媒体字段并仅为非空字段创建按钮的 for 循环?

  • 你能显示你的html代码吗?

标签: python django django-models


【解决方案1】:

如果您的链接不在 HTML 中的 for 循环中。我建议您对每个社交媒体链接使用 if 块。

例子是:

{% if profile.linkedin %}
 <a href="{% url 'profile.linkedin' %}">LinkedIn</a>
{% if profile.spotify %}
 <a href="{% url 'profile.spotify' %}">Spotify</a>
{% else %}
{% endif %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 2021-01-06
    相关资源
    最近更新 更多