0
votes

i hope you can help me, im trying to make a django post form without reloading the page using ajax, but im getting error 500 when submit, can you help me to fix this, this is my code:

models.py

class ProductoConcepto(models.Model):
    producto = models.ForeignKey(Producto)
    orden = models.ForeignKey(Cobro)
    cantidad = models.FloatField()

urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
from cobro import views

urlpatterns = [
    url(r'^cobro/agregar_concepto/$', views.addconcept_product, name='add_concepto'),
]

views.py

def addconcept_product(request):

    if request.method == 'POST':

        if form.is_valid():
            producto = request.POST['producto']
            orden = request.POST['orden']
            cantidad = request.POST['cantidad']

            ProductoConcepto.objects.create(producto=producto, orden=orden, cantidad=cantidad)

            return HttpResponse('')

template

    <div class="modal inmodal fade" id="myModal1" tabindex="-1" role="dialog"  aria-hidden="true">
            <div class="modal-dialog modal-m">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">
                            <span aria-hidden="true">&times;</span>
                            <span class="sr-only">Cerrar</span>
                        </button>
                        <h3 class="modal-title">Agregar nuevo concepto</h3>
                    </div>
                    <div class="modal-body">
                        <p>Datos de concepto a agregar:</p>
                        <div class="doctorformstyle">
                        <form id='formulario-modal' method='post' enctype='multipart/form-data'>
                            {% csrf_token %}
                            <ul>{{form2.as_p}}</ul>

<!--  rendered form2 fields: <select id="id_producto" name="producto"><option value="1" selected="selected">object</option></select> -->
<!--  form2 fields: <select id="id_orden" name="orden">
<option value="1" selected="selected">object</option>
</select> -->
<!--  form2 fields: <input id="id_cantidad" name="cantidad" step="any" type="number"> -->

                            <div class="row align-center">
                                <input type='submit' name="save1" value='Guardar' class="btn btn-w-m btn-primary"/>
                            </div>

                        </form>
</div>
                    </div>
                </div>
            </div>
        </div>

<script type="text/javascript">
    $(document).on('submit', '#formulario-modal', function(e){
            e.preventDefault();
            $.ajax ({
                type: 'POST',
                url: '{% url 'add_concepto' %}',
                data: {
                    producto: $('#id_producto').val(),
                    orden: $('#id_orden').val(),
                    cantidad: $('#id_cantidad').val(),
                    csrfmiddlewaretoken: '{{ csrf_token }}',
                },
                sucess:function(){
                    alert("OK");
                }
            })
    });

</script>

this is the error: POST http://127.0.0.1:8000/cobro/agregar_concepto/ 500 (Internal Server Error)

I think that maybe something is missing in my view, buy i dont know that, cal you help me?

Edit: Traceback added

Environment:

Request Method: GET Request URL: http://127.0.0.1:8000/cobro/agregar_concepto/

Django Version: 1.9.7 Python Version: 2.7.11 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'entrada', 'cobro', 'catalogo', 'selectize', 'smart_selects') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response 158. % (callback.module, view_name))

Exception Type: ValueError at /cobro/agregar_concepto/ Exception Value: The view cobro.views.addconcept_product didn't return an HttpResponse object. It returned None instead.

3
Please show the full error traceback. I think some exception is getting raised.kapilsdv
sure, i edited the post.Kevin Ramirez Zavalza
So its clear from the error that you are returning None from the view, and that's why you are getting the exception and a 500 status.Atleast return something like return HttpResponse('Product Created !')kapilsdv
can you explain me how to fix that, i'm still learning this and sometimes i can't see the errors so clearly, also thanks for answering.Kevin Ramirez Zavalza

3 Answers

0
votes

You view is not complete: As the exception states: The view cobro.views.addconcept_product didn't return an proper HttpResponse object.

return HttpResponseRedirect('/thanks/')
0
votes

Are you viewing the exception you provided in a new window? Because it is showing "Request Method: GET" which shouldn't be happening via your ajax function.

Modify your view to this:

def addconcept_product(request):

    if request.method == 'POST':

        if form.is_valid():
            producto = request.POST['producto']
            orden = request.POST['orden']
            cantidad = request.POST['cantidad']

            ProductoConcepto.objects.create(producto=producto, orden=orden, cantidad=cantidad)

            return HttpResponse('Product Created')
        else:
            return HttpResponse('Product Creation failed')
    else:
        return HttpResponse('Failed: Post requests only.')
0
votes

Update your return statement with something like.

return HttpResponse('Product Created !')

Also as you are using ajax, you can also return a JsonResponse.

First import it

from django.http import JsonResponse

and then return your response

JsonResponse({'success': 'Product created'})

The exception is getting raised because you are not handling the condition if the method is not POST, and you are submitting a GET request.

Handle the cases for invalid form and if method is not POST.

def addconcept_product(request):

if request.method == 'POST':

    if form.is_valid():
     ....

        return JsonResponse({'success': 'Product created'})
    else:
        return JsonResponse({'error': 'InValid Form.Product Creation Failed'})
else:
    return JsonResponse({'error': 'Only POST method allowed'})

Also use ajax method attribute instead of type.

$.ajax ({
          method: 'POST',
          url: '{% url 'add_concepto' %}',
    ....
    });