Help with django form an ajax, error 500

1,090 views
Skip to first unread message

Elros Romeo

unread,
Jul 15, 2016, 7:49:00 PM7/15/16
to Django users
Hi, 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)

ludovic coues

unread,
Jul 16, 2016, 7:20:55 AM7/16/16
to django...@googlegroups.com
The error should come with a backtrace. Providing the backtrace will
help a lot in finding the error.
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/f17e5677-4401-41e4-a928-326a23b3c6fa%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



--

Cordialement, Coues Ludovic
+336 148 743 42

Andrew Beales

unread,
Aug 10, 2016, 7:46:26 AM8/10/16
to Django users
Guessing this is old news, but there are 2 problems with views:

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

- producto and orden need to be Python objects and cantidad is a float, but the request.POST values will be string representations.

Also the ajax post doesn't involve the forms API, so no 'if form.is_valid()'

You'd need to do something like this:

        if request.method == 'POST':

            producto = Producto.objects.get(name=request.POST['producto'])
            orden = etc.
            cantidad = float(etc)

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

agapito treviño

unread,
Aug 17, 2016, 9:34:33 PM8/17/16
to Django users
Elros Romeo

as defined by the form.as_p.?
I want to implement this
Message has been deleted

Constantine Covtushenko

unread,
Aug 18, 2016, 12:45:40 AM8/18/16
to Django users
Sorry guys, please skip my previous post. It appeared unfinished.
My correct one below.

Hi Andrew,

To have a proper `to_python` transformation from `POST` strings please use forms.
They do that perfectly and also they can handle any king of user input validations.

form = SomeCustomForm(request.POST)
if form.is_valid():
parsed_dictionary = form.cleaned_data()
//some other required stuff


As for 'Ajax'. It seems like you should manually parse body before any further processing. Request instance has `is_ajax` method to detect such requests.

That can be done
import json
if request.is_ajax():
query_dict =  json.loads(request.body)

I hope it helps.

Regards,
Constantine C.

Fred Stluka

unread,
Aug 21, 2016, 10:08:36 AM8/21/16
to django...@googlegroups.com
Elros Romeo,

Can you see the log file?  It may show details of the 500 error,
which will likely be some error reported by your Django code.
Could be anything from a Python syntax error to a failed attempt
to connect to a DB, to a misconfigured settings file, or anything
else.

--Fred

Fred Stluka -- mailto:fr...@bristle.com -- http://bristle.com/~fred/
Bristle Software, Inc -- http://bristle.com -- Glad to be of service!
Open Source: Without walls and fences, we need no Windows or Gates.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
Reply all
Reply to author
Forward
0 new messages