ailsin
ailsin

Reputation: 35

How to throw django 404 error as error message on the same page

I am trying to query an instance of a particular model, FoodRedistributor and I would like to throw a pop up error message on the same page if a FoodRedistributor of the given name does not exist. I tried doing Http404 but that redirects me to a 404 page which is not how I would like the user to see the error. Using the messages.info does not give me any output.

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.")

Upvotes: 0

Views: 279

Answers (1)

SANGEETH SUBRAMONIAM
SANGEETH SUBRAMONIAM

Reputation: 1086

  1. If you are okay with using messages like error

    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. PASS THE errormessage to the template through the context dictionary and rerender the same page

  3. Render the error message in the template if error message exist

    template.html

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

Else you can use JS to create a pop up based on passed error message value

Upvotes: 1

Related Questions