How would i return error message with django? I am thinking something like this ( i am using jsonresponse just as an example of how i want to do this):
def test(request):
if request.method == "POST":
if form.is_valid():
form.save
return JsonResponse({"message":"Successfully published"})
else:
'''here i would like to return error something like:'''
return JsonResponse({"success": false, "error": "there was an error"})
else:
return JsonResponse({"success}: false, "error": "Request method is not post"})
What I am trying to achieve is to render error messages in template from ajax error function. Something like this:
$("#form").on("submit", function(){
$.ajax({url: "url",
data: ("#form").serialize,
success: function(data){
alert(data.message);
},
error: function(data){
alert(data.error);
}
});
Would that be possible?
You can of course return error messages from your Django App. But you have to define what type of error you want to return. For this purpose you'll have to use error codes.
The most known are 404 for page not found or 500 for a server error. You can also have 403 for a forbidden access... It depends of the case you want to treat. You can see the wikipedia page for a view of the possibilities.
Instead of sending a 'success':False
use this :
response = JsonResponse({"error": "there was an error"})
response.status_code = 403 # To announce that the user isn't allowed to publish
return response
With this jQuery will recognize the answer as an error and you will be able to manage the error type.
To manage your errors in JavaScript :
$("#form").on("submit", function(){
$.ajax({
url: "url",
data: ("#form").serialize,
success: function(data){
alert(data.message);
},
error: function(data){
alert(data.status); // the status code
alert(data.responseJSON.error); // the message
}
});
Try this. I think there is a syntax error in your code. Also, it will be better if you post your error message. I changed the false
to False
Also did you omit your form instance in your code.
def test(request):
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
form.save()
return JsonResponse({"message":"Successfully published"})
else:
'''here i would like to return error something like:'''
return JsonResponse({"success": False, "error": "there was an error"})
else:
return JsonResponse({"success}: False, "error": "Request method is not post"})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With