0

I'm trying to show dynamicly details of a certain object, getting them from a sqlite3 database. I based my code on a tutorial, everything is exactly the same, but I get a 500 Internal Server Error on my page (but the tutorial runs perfectly).

I have python 3.3 and django 1.6 installed.

Here's my code:

url.py :

url(r'^cargar-inmueble/(?P<id>\d+)$', 'inmobiliaria.views.cargar_inmueble', name='cargar_inmueble_view'),

views.py :

import json
from django.http import HttpResponse, Http404
from inmobiliaria.models import *

....

def cargar_inmueble(request, id):
    if request.is_ajax():
        inmueble = Inmueble.objects.get(id=id)
        return HttpResponse( json.dumps({'nombre': inmueble.nombre,
        'descripcion': inmueble.descripcion, 'foto' : inmueble.foto }),
        content_type='application/json; charset=utf8')
    else:
        raise Http404

hover.js (it's the main js script, have to rename it)

$(document).on("ready", inicio );

function inicio() {

    ...

    $("#slider ul li.inmueble").on("click", "a", cargar_inmueble);
}

function cargar_inmueble(data) {

    var id = $(data.currentTarget).data('id');

    $.get('cargar-inmueble/' + id, ver_inmueble);

}

Looking at the console of the chrome dev tools, everytime I click the link that calls "cargar_inmueble", I get this error and "ver_inmueble" is never called.. It's my first web site using python so I'm pretty lost!

4

1 回答 1

0

检查 chrome 开发工具的网络选项卡,然后您就会知道问题的根源。

另一种调试方法是简化您的视图:

def cargar_inmueble(request, id):
    inmueble = Inmueble.objects.get(id=id)
    return HttpResponse( json.dumps({'nombre': inmueble.nombre,
        'descripcion': inmueble.descripcion, 'foto' : inmueble.foto }),
        content_type='application/json; charset=utf8')

然后直接去,http://localhost:8000/cargar-inmueble/1如果你离开DEBUG=True,你会看到堆栈跟踪settings.py

此行很可能会导致错误:

inmueble = Inmueble.objects.get(id=id)

id不存在时,它会抛出 DoesNotExist 异常,你应该抓住它。此外,我相信返回 JSON 与您正在做的事情有点不同:

def cargar_inmueble(request, id):
    try:
        inmueble = Inmueble.objects.get(id=id)
    except Inmueble.DoesNotExist: # catch the exception
        inmueble = None

    if inmueble:
        json_resp = json.dumps({
            'nombre': inmueble.nombre,
            'descripcion': inmueble.descripcion, 
            'foto' : inmueble.foto 
        })
    else:
       json_resp = 'null'

    return HttpResponse(json_resp, mimetype='application/json')

当然,您可以使用get_object_or_404更简单的代码。我只是想展示基本的想法。

希望能帮助到你。

于 2013-08-03T23:29:09.053 回答