【问题标题】:How to use messages in Django?如何在 Django 中使用消息?
【发布时间】:2014-08-26 17:36:02
【问题描述】:

下面,我有这个div,负责显示任何错误警告成功消息。但我只知道如何将它与成功案例一起使用。

这是我的 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,})

这是我的 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>

我的问题是:如何验证我的字段并在我的 html 页面中显示一切是否正常?

例如,有一个checkbox表示使用条款的协议,对吧?如果用户没有检查,我如何使用这些消息告诉用户他需要接受使用条款才能注册。

【问题讨论】:

    标签: python django python-2.7 django-forms django-views


    【解决方案1】:

    使用clean方法怎么样?

    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
    

    【讨论】:

      【解决方案2】:

      为什么你不使用 JavaScript 来显示你的消息?它非常优雅,具有更多的性能!你可以使用这样的函数:

      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");
      };
      

      但是关于验证表单的问题,请阅读 THIS 好方法!你也可以使用 Django 教程中的 THIS ONE

      【讨论】:

      • 抱歉,我不明白这些链接与我的问题有何关联。
      • 因为我读到了“如何验证我的字段并在我的 html 页面中显示一切是否正常”
      • 我现在不想使用 JavaScript,也不想和 Django 混在一起,因为我专注于学习 Python + Django。而且我相信应该有一个使用 Django 本身的解决方案。
      • 知道了,我会更新我的问题,然后更具体一点。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 2023-03-31
      • 2012-04-25
      • 1970-01-01
      • 2020-06-04
      • 2011-05-20
      • 1970-01-01
      相关资源
      最近更新 更多