【问题标题】:HTTP 500 error in Django while getting data using AJAX使用 AJAX 获取数据时 Django 中的 HTTP 500 错误
【发布时间】:2016-04-03 09:21:47
【问题描述】:

下面是我的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')

以下是模型中的模型。 py:

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'

【问题讨论】:

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


    【解决方案1】:

    由于这一行,您的代码无法正常工作:

    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 dict 并直接将值分配给“名称”键。您应该在填充之前定义它。

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

    【讨论】:

    • 我按照你说的尝试了,但你看到同样的错误仍然存​​在。作为编辑,我还复制了我的问题中的错误
    • 在浏览器的网络选项卡中,您将能够看到完整的回溯。请放完整的追溯。简单的状态码无助于调试
    • 我按你说的试过了。它不起作用。我的完整回溯在编辑后的问题中
    • @SGangs 你的代码中有错字。应该是Customer.objects 而不是Customer.object
    • 也许这正在发生json 阴影模块json。将变量重命名为 data_json 之类的其他名称,它应该可以工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多