简体   繁体   English

如何在Django中使用消息?

[英]How to use messages in Django?

Below, I have this div that is responsible to show any error , warning and success message. 下面,我有这个div负责显示任何错误警告成功消息。 But I figure out how to use it with the success case only. 但是我想出了如何仅在成功案例中使用它。

This is my views.py 这是我的views.py

def registration(request):
    form = PersonForm(request.POST or None)

    if form.is_valid():
        save_it = form.save(commit=False)
        save_it.save()
        messages.success(request, 'Your form was saved') 

     <if checkbox not checked>  <<< is this possible ?
       messages.error(request, 'You must accept the terms to register')

    return render(request, 'provisioning/registration.html', {'form':form,})

And this is my registration.py 这是我的registration.py

    <div>
        ...
        {% if messages %}
            {% for message in messages %}
            <div {% if message.tags %} class="alert alert-{{ message.tags }}" {% endif %} alert-danger fade in">
                <button data-dismiss="alert" class="close close-sm" type="button">
                    <i class="fa fa-times"></i>
                </button>
                <strong>{{ message.tags }} | </strong> {{message}}
            </div>
            {% endfor %}
        {% endif %}
    </div>

My question is: how can I validate my fields and show if everything went fine or not in my html page ? 我的问题是:如何验证我的字段并在html页面中显示一切正常?

For example, there is a checkbox for the agreement of terms of use, right ? 例如,有一个使用条款协议的checkbox ,对吗? How can I use the messages to tell to the user that he need to accept the terms of use to register in case if wasn't checked by the user. 如果用户未检查,我如何使用消息告诉用户他需要接受使用条款进行注册。

How about using clean method? 使用清洁方法怎么样?

def clean_agreement(self):
        data = self.cleaned_data
        if not data['agreement']:
            msg = u"You have to agree with the terms and conditions."
            self._errors["agreement"] = self.error_class([msg])
            return False
        return True

Why you don't use JavaScript for show your messages ? 为什么不使用JavaScript显示消息? its very elegant and have more performance ! 它非常优雅并且有更多表现! you can use a function like this : 您可以使用如下功能:

var showMessage = function(element, msg, where) {
    var div = $('<div class="your_classname"><h3>' +msg+ '</h3>(' +
    gettext('click to close') + ')</div>');
    div.click(function(event) {
        $(".your_class_name").fadeOut("fast", function() { $(this).remove(); });
    });

    var where = where || 'parent';

    if (where == 'parent'){
        element.parent().append(div);
    }
    else {
        element.after(div);
    }

    div.fadeIn("fast");
};

but about your question for validating forms read THIS good recipe ! 但是关于您的验证表格问题,请阅读好食谱! also you can use THIS ONE from Django tutorial ! 您也可以使用Django教程中的THIS ONE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM