Following is my views.py function, that takes in customer key as AJAX input from user and checks the database and returns the customer name.
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')
Following is the model in models. 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
However, after the AJAX call I'm getting a HTTP 500 error.
I dont know why. Can someone please elaborate.
For your further needful, following is the AJAX call to the django view.
(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
},
});
}());
Edit 1
Following is the error shown in the console:
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
The anonymous function is the ajax function, that I've copied above
Update
Following is the traceback, after I put customer data and the AJAX call starts:
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'
Your code is not working properly because of this line:
response_data['name'] = Customer.objects.name(customer_key=customerkey)
Is should be something like:
response_data['name'] = Customer.objects.get(customer_key=customerkey).name
I would suggest to catch exception if the object is not found to avoid further errors.
try:
customer = Customer.objects.get(customer_key=customerkey)
response_data['name'] = customer.name
except Customer.DoesNotExists:
show_error_response()
Update : I just noticed that you haven't defined response_data
dict and are directly assigning values to 'name' key. You should define it before populating it.
response_data = {}
response_data['name'] = Customer.objects.name(customer_key=customerkey)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.