我正在嘗試查詢特定模型 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.")
uj5u.com熱心網友回復:
如果您可以使用錯誤等訊息
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通過背景關系字典將錯誤訊息傳遞給模板并重新渲染同一頁面
如果存在錯誤訊息,則在模板中呈現錯誤訊息
模板.html
<!-- template headers --> {% if errormessage %} <p style="color:red;"> {{errormessage}} </span> {% endif %} <!-- template rest of content-->
否則,您可以使用 JS 根據傳遞的錯誤訊息值創建彈出視窗
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/345159.html
上一篇:如何從字串中洗掉回文單詞
