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.")
CodePudding user response:
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
PASS THE errormessage to the template through the context dictionary and rerender the same page
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