【问题标题】:How to throw django 404 error as error message on the same page如何在同一页面上将 django 404 错误作为错误消息抛出
【发布时间】:2021-11-02 04:34:08
【问题描述】:

我正在尝试查询特定模型 FoodRedistributor 的实例,如果给定名称的 FoodRedistributor 不存在,我想在同一页面上弹出一条错误消息。我尝试做 Http404 但这会将我重定向到 404 页面,这不是我希望用户看到错误的方式。使用 messages.info 并没有给我任何输出。

if request.method == "POST":
         username = request.POST.get("username")
         password = request.POST.get("password")
         try:
             user = FoodRedistributor.objects.get(name=username)
         except:
            raise Http404("No food redistributor matches the given query.")

【问题讨论】:

    标签: python-3.x django


    【解决方案1】:
    1. 如果您可以使用错误等消息

      if request.method == "POST":
           username = request.POST.get("username")
           password = request.POST.get("password")
           try:
               user = FoodRedistributor.objects.get(name=username)
           except:
              errormessage = 'No food redistributor matches the given query.'
              #raise Http404("No food redistributor matches the given query.")
      
      #render template with errormessage
      
    2. 通过上下文字典将错误消息传递给模板并重新呈现同一页面

    3. 如果存在错误消息,则在模板中呈现错误消息

      template.html

      <!-- template headers -->
      
      {% if errormessage  %}
          <p style="color:red;"> {{errormessage}} </span>
      {% endif %}
      
      <!-- template rest of content-->
      

    否则,您可以使用 JS 根据传递的错误消息值创建弹出窗口

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      相关资源
      最近更新 更多