Home > Software design >  404 (Not Found) error on ajax post request
404 (Not Found) error on ajax post request

Time:07-13

This code is meant to get data from a form and request a Django view to create an account in a database and respond with an instant of the account created, back to the template.html which made the previous request.

The form is created using django-crispy-forms and there are two views, one for creating a form on the template and the other for processing the submitted form data from the Ajax post request

template.html

 <div class ="center">
   <form action="" novalidate>
     <input name="csrfmiddlewaretoken" type="hidden" value="{{csrf.value}}>
     {% crispy form form.helper %}
   </form>
</div>

{% block script %}
<script src="{% static 'js/ajaxSubmit.js' %}"></script>
{% endblock script %}

views.py

def formView(request, pk):
 profile = get_object_or_404(Profile, pk=pk)
 form = AccountForm()
 return render (request, template.html,{'profile':profile, 'form':form})

def postAccount(request, pk):
 profilé = get_object_or_404(Profile, pk=pk)
 if request.is_ajax and request.method == 'POST':
  form = AccountForm ( request.POST)
  if form.is_valid():
   instance = form.save()
   ser_instance = serializers.serialize('json', [instance,])
   return JsonResponse({"instance":ser_instance}, status=200)
  else:
   return JsonResponse ({"error":form.errors}, status=400)
 return JsonResponse ({"error":"", status=400)

urls.py

#other urls,
re_path(r'^home/(?P<pk>\d )/new/$', views.formView, name="formViews"),
re_path(r'^home/(?P<pk>\d )/new/$', views.postAccount, name="postAccount"),

ajaxSubmit.js

$("form").on("submit", function (e) {
 var dataString = $(this).serialize();
 $.ajax({
   type: "POST",
   url:"{% url 'postAccount' profile.pk %}",
   data: dataString,
   contentType: "json",
   success: function (response){
    var instance = JSON.parse(response ["instance"]);
    alert(instance.name);
   },
   error: function(response){
    alert(response.message)
   }
 e.preventDefault();
});

after I submit the form, my chrome browser console produces the following issues

POST http://127.0.0.1:8000/app/home/2/new/{%url 'postAccount profile.pk 6E 404 (Not Found)

CodePudding user response:

You can not use django template tag for standalone javascript: here is the error:

url:"{% url 'postAccount' profile.pk %}"

Of course you can made render js, and after that you can save it. In your case it should be:

url:"", // in your case url is already exists.

But you have the same url for ForView and for form Account, it think, you always call the first 'formViews'

#other urls,
re_path(r'^home/(?P<pk>\d )/new/$', views.formView, name="formViews"),
re_path(r'^home/(?P<pk>\d )/new/$', views.postAccount, name="postAccount"),
  • Related