使用AJAX获取数据时Django中的HTTP 500错误

时间:2016-04-03 09:21:47

标签: python ajax django django-models django-views

以下是我的views.py函数,它将客户密钥作为用户的AJAX输入接收并检查数据库并返回客户名称。

def bill(request):

if request.method == 'POST':
    customerkey = request.POST.get('customer_code')
    response_data['name'] = Customer.object.name(customer_key=customerkey)
    json = json.dumps(response_data)
    return HttpResponse(json, mimetype='application/json')
return render(request, 'bill/invoicing.html')

以下是模型中的模型。吡啶:

class Customer (models.Model):
name=models.CharField(max_length=300, unique=True)
zone=models.ForeignKey(Zone,related_name='customer_zone', verbose_name='Zone')
slug=models.SlugField(max_length=300)
customer_key=models.CharField(max_length = 10, unique=True)
address=models.TextField(unique=True)
phone_no=models.TextField
details=models.TextField(blank=True)
object = models.Manager()

def get_absolute_url(self):
    return reverse('billbrain:master_detail', kwargs={'detail':self.slug})


def save(self, *args, **kwargs):
    if not self.id:
        self.slug=slugify(self.name)

    super(Customer, self).save(*args, **kwargs)


class Meta:
    ordering = ('name',)


def __str__(self):
    return self.name

但是,在AJAX调用之后,我收到了HTTP 500错误。

我不知道为什么。有人可以详细说明。

对于您的进一步需求,以下是对django视图的AJAX调用。

(function() {
    console.log("AJAX about to start") // sanity check
    $.ajax({
        url : "", 
        type : "POST", 
        data : { customer_code: input,
                 'csrfmiddlewaretoken': csrf_token}, // data sent with the post request

                // handle a successful response
        success : function(json) {
            console.log(json); // log the returned json to the console
            console.log("success"); // another sanity check
        },

        });
}());

修改1

以下是控制台中显示的错误:

POST http://localhost:8000/master/sellbill/ 500 (INTERNAL SERVER ERROR)
send @ jquery.min.js:4
n.extend.ajax @ jquery.min.js:4
(anonymous function) @ script.js:260
(anonymous function) @ script.js:277
n.event.dispatch @ jquery.min.js:3
r.handle @ jquery.min.js:3

匿名函数是我在上面复制的ajax函数

更新

以下是追踪,在我放置客户数据并开始AJAX调用之后:

UnboundLocalError at /master/sellbill/
local variable 'json' referenced before assignment

Request Method: POST
Request URL: http://localhost:8000/master/sellbill/
Django Version: 1.8.6
Python Executable: C:\Users\Ganguly          PC\Desktop\DjangoStudy\my_env\Scripts\python.exe
Python Version: 3.5.1
Python Path: ['C:\\Users\\Ganguly PC\\Desktop\\DjangoStudy\\billinv',  'C:\\Users\\Ganguly PC\\Desktop\\DjangoStudy\\my_env\\lib\\site-packages\\pytz- 2015.7-py3.5.egg', 'C:\\Users\\Ganguly  PC\\Desktop\\DjangoStudy\\my_env\\Scripts\\python35.zip', 'C:\\Users\\Ganguly  PC\\Desktop\\DjangoStudy\\my_env\\DLLs', 'C:\\Users\\Ganguly PC\\Desktop\\DjangoStudy\\my_env\\lib', 'C:\\Users\\Ganguly PC\\Desktop\\DjangoStudy\\my_env\\Scripts', 'c:\\python35-32\\Lib',  'c:\\python35-32\\DLLs', 'C:\\Users\\Ganguly PC\\Desktop\\DjangoStudy\\my_env', 'C:\\Users\\Ganguly PC\\Desktop\\DjangoStudy\\my_env\\lib\\site-packages']
Server time: Sun, 3 Apr 2016 10:11:43 +0000
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'billbrain',
 'bootstrap_themes')
 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',
 'django.middleware.security.SecurityMiddleware')

Traceback:
File "C:\Users\Ganguly PC\Desktop\DjangoStudy\my_env\lib\site-packages\django\core\handlers\base.py" in get_response
132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Ganguly PC\Desktop\DjangoStudy\billinv\billbrain\views.py" in  bill
118.        json = json.dumps(response_data)

Exception Type: UnboundLocalError at /master/sellbill/
Exception Value: local variable 'json' referenced before assignment
Request information:
GET: No GET data

POST:
customer_code = 'FR'
csrfmiddlewaretoken = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

FILES: No FILES data

COOKIES:
csrftoken = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
toShowIxigo = '1'

1 个答案:

答案 0 :(得分:0)

由于以下行,您的代码无法正常运行:

response_data['name'] = Customer.objects.name(customer_key=customerkey)

应该是这样的:

response_data['name'] = Customer.objects.get(customer_key=customerkey).name

如果找不到对象以避免进一步的错误,我建议捕获异常。

try:
    customer = Customer.objects.get(customer_key=customerkey)
    response_data['name'] = customer.name
except Customer.DoesNotExists:
    show_error_response()

<强>更新: 我刚刚注意到您还没有定义response_data字典,而是直接将值分配给&#39; name&#39;键。您应该在填充之前定义它。

response_data = {}
response_data['name'] = Customer.objects.name(customer_key=customerkey)