Reputation: 879
I am using try except to handle errors in views.py. In the exception area i want to redirect user to a template if there is an error. While redirecting to the template, i want to pass errors to template and show errors at the beginning of that page.
try:
car.delete()
except ProtectedError, e:
return redirect(reverse('car-operations') + '?car_no=' + str(car.car_no), {'errors': e})
The ProtectError occurs when i try to delet the car. But this error is not passed to redirected page. In redicreted page i use below code to show errors.
{% if errors %}<div class="alert alert-danger">{{ errors }}</div>{% endif %}
I see that error occurs. But i couldn't pass it to template. If i use render request, i can pass the error to template but this time i can't call the template with "'?car_no=' + str(car.car_no)"
Upvotes: 1
Views: 1391
Reputation: 434
it is because you can't pass context to redirect, but for passing the errors to front end you can use something like django message
from django.contrib import messages
try:
car.delete()
except ProtectedError, e:
messages.add_message(request, messages.ERROR, e)
and in templates to show the error you use this
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
for reference you can check https://docs.djangoproject.com/en/2.1/ref/contrib/messages/
Upvotes: 3