How can I add additional data to Django messages?

前端 未结 2 1747
礼貌的吻别
礼貌的吻别 2020-12-17 05:01

I\'m trying to integrate this snippet into our Django project:

It\'s just custom HTML and CSS for messages.

The html l

相关标签:
2条回答
  • 2020-12-17 05:12

    You can get certain amount of freedom using the extra_tags messages attribute.

    See https://docs.djangoproject.com/en/1.11/ref/contrib/messages/#adding-extra-message-tags

    So you could have different extra_tags for different calls to action, e.g.

    # views.py
    messages.success(request, 'You have signed up', extra_tags='suggest_upgrade')
    

    or:

    messages.success(request, 'You have signed up', extra_tags='suggest_share')
    

    and then:

    {% for message in messages %}
    
        {% if 'suggest_upgrade' in message.extra_tags %}
            <h1>Get these extra features</h1>
            <p>info here</p>
        {% elif 'suggest_share' in message.extra_tags %}
            <h1>Share with friends</h1>
            <p>other info here</p>
        {% endif %}
    
    {% endfor %}
    

    You could even pass a submessage as the tag itself although it’s probably not designed for that purpose:

    messages.success(request, 'Main message here', extra_tags='submessage here')
    

    and then:

    {% for message in messages %}
    
        <h1>{{ message }}</h1>
        <p>{{ message.extra_tags }}</p>
    
    {% endfor %}
    
    0 讨论(0)
  • 2020-12-17 05:32

    Message doesn't necessary needs to be a string. In your case, using a dictionary would work just fine:

    messages.success(request, {'title':'This is a title','submessages':[1,2,3]})
    

    and then in your template:

    {% for message in messages %}
        <div class="bs-calltoaction bs-calltoaction-{{ message.tags }}">
            <div class="row">
                <div class="col-md-9 cta-contents">
                    <h1 class="cta-title">{{ message.message.title }}</h1>
                    <div class="cta-desc">
                        <p>{{ message.message.submessages.0 }}</p>
                        <p>{{ message.message.submessages.1 }}</p>
                    </div>
                </div>
                <div class="col-md-3 cta-button">
                    <a href="#" class="btn btn-lg btn-block btn-default">Go for It!</a>
                </div>
             </div>
        </div>
    {% endfor %}
    
    0 讨论(0)
提交回复
热议问题