Delete all documents in a MongoDB collection via Django backend and Angular frontend - django

I have managed to write code to add a customer to my MongoDB collection from my Angular service method to my Django http function, as follows:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json'
}),
withCredentials: false
}
#Injectable()
export class MongoService {
myApiBaseUrl = "http://localhost:8000/mydjangobaselink/";
constructor(private httpClient: HttpClient) { }
addCustomer(customerFormInfo: Customer): Observable<Customer> {
return this.httpClient.post<Customer>(`${this.myApiBaseUrl}`, JSON.stringify(customerData), httpOptions);
}
deleteCustomer(): Observable<Customer> {
return this.httpClient.delete<Customer>(`${this.myApiBaseUrl}`);
}
}
#csrf_exempt
#api_view(['GET', 'POST', 'DELETE'])
def handle_customer(request):
if request.method == 'POST':
try:
customer_data = JSONParser().parse(request)
customer_serializer = CustomerModelSerializer(data=customer_data)
if customer_serializer.is_valid():
customer_serializer.save()
# Write customer data to MongoDB.
collection_name.insert_one(customer_serializer.data)
response = {
'message': "Successfully uploaded a customer with id = %d" % customer_serializer.data.get('id'),
'customers': [customer_serializer.data],
'error': ""
}
return JsonResponse(response, status=status.HTTP_201_CREATED)
else:
error = {
'message': "Can not upload successfully!",
'customers': "[]",
'error': customer_serializer.errors
}
return JsonResponse(error, status=status.HTTP_400_BAD_REQUEST)
except:
exceptionError = {
'message': "Can not upload successfully!",
'customers': "[]",
'error': "Having an exception!"
}
return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
elif request.method == 'DELETE':
try:
CustomerModel.objects.all().delete()
# Delete customer data from MongoDB.
collection_name.deleteMany({})
return HttpResponse(status=status.HTTP_204_NO_CONTENT)
except:
exceptionError = {
'message': "Can not delete successfully!",
'customers': "[]",
'error': "Having an exception!"
}
return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
The POST method works fine and I can see the added document in my MongoDB Compass, but when I try to delete, I get:
DELETE http://localhost:8000/mydjangobaselink/ 500 (Internal Server Error)
All the posts and articles I have seen address communication issues in the browser, local host, etc... but given that my posting method works fine, I don't think that is my issue. Also, in Postman, I get Can not delete successfully!
Can anyone see what might be wrong that I cannot delete from database?

Try with collection_name.delete_many({})
https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.delete_many
Edit: as pointed by #NKSM, there is the documentation copied:
delete_many(filter, collation=None, hint=None, session=None)
Delete one or more documents matching the filter:
>>> db.test.count_documents({'x': 1})
3
>>> result = db.test.delete_many({'x': 1})
>>> result.deleted_count
3
>>> db.test.count_documents({'x': 1})
0

Related

Calling Ajax from django template fails with error: Field 'id' expected a number but got 'populate_sections'

I have one URL in urls.py file as given below:-
urlpatterns = [
........
path('edit_student/<student_id>', views.edit_student, name="edit_student"),
path('populate_sections', views.populate_sections, name="populate_sections"),
..........
]
In views.py file edit student function is defined as follows:
#login_required
def edit_student(request, student_id):
form = UpdateStudentForm()
context = {
"form": form
}
return render(request, "edit_student.html", context)
Now the template edit_student.html has a Ajax call:-
$("#id_class_name").change(function(){
var class_name = $(this).val();
$.ajax({
url: 'populate_sections',
type: 'GET',
data: {class_name:class_name},
dataType: 'json',
success: (data) => {
$("#id_section_name").empty();
for( var i in data.context){
$("#id_section_name").append("<option value='"+data.context[i].id+"'>"+data.context[i].name+"</option>");
}
}
});
});
The views.py file function populate_section is declared as follows:-
#login_required
def populate_sections(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax:
if request.method == 'GET':
class_name = request.GET.get("class_name")
class_object = Classes.objects.get(id=class_name)
sections = Sections.objects.filter(classes=class_object)
return JsonResponse({'context': list(sections.values())})
return JsonResponse({'status': 'Invalid request'}, status=400)
else:
return HttpResponseBadRequest('Invalid request')
Whenever i change the field which triggers Ajax function call i am getting the value error:
ValueError at /edit_student/populate_sections
Exception Value:
Field 'id' expected a number but got 'populate_sections'.
I understand that it is expecting the student id but how to do that.
Thanks & Regards
Neha Singh

Why is flask jsonify returning unidentified?

I am using fetch on the frontend to send data to my flask backend in order to make a movie seat booking. The whole process works fine until the client awaits the response, which is "undefined" . So , basically the database saves the data , the only problem is the response which is sent to the client. I used jsonify which usually works fine. Can anybody tell me what I am missing? Thanks in advance.
Here is the JS code :
function sendReservationToServer() {
const selectedSeats = sessionStorage.getItem('selectedSeats')
const reservation = { userId, selectedSeats, showTimeId, movieHallId }
fetch('/bookSeats', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(reservation)
}).then(response => {
response.json()
}).then(data => {
theatreHall.innerHTML = `${data} <br> <a href='/home'>Back to main menu</a>`
console.log(`${data}`)
}).catch(err => infoMsg.textContent = err)
sessionStorage.clear()
}
And this is the flask controller which handles the request:
#app.route("/bookSeats", methods=["POST"])
def book_seats():
selected_seats = request.json
user_id = selected_seats.get('userId')
seats = json.loads(selected_seats.get('selectedSeats'))
movie_hall_id = selected_seats.get('movieHallId')
seat_ids = []
showtime_id = selected_seats.get('showTimeId')
for seat in seats:
seat_ids.append(db.session.query(Seat).filter(
Seat.seat_number == seat).filter(Seat.movie_hall_id == movie_hall_id).all()[0].stid)
for seat in seat_ids:
reserved_seat = ReservedSeat(
seat_id=seat, show_time=showtime_id, user=user_id)
db.session.add(reserved_seat)
db.session.commit()
reservation = Reservation(
user=user_id, show_time=showtime_id, number_of_tickets=len(seat_ids))
db.session.add(reservation)
db.session.commit()
message = f'{seats} booked successfully'
return jsonify(message)
data is undefined because the first then does not return anything. Either make it return response.json() or move everything in the second then to the first and replace data with response.json().

How to pass django serializers Validation Error of a field to React as json fromat

In my rest framework user registration form I successfully created a custom registration form and added some validators. It shows corresponding validation errors in rest framework.but when linked this to react through redux it gets the error but not showing corresponding validation errors like " A user is already registered with this e-mail address. ".
The rest showsit like this.
JSON format that gets at react is this
error: {
message: 'Request failed with status code 400',
name: 'Error',
fileName: 'http://localhost:3000/static/js/1.chunk.js',
lineNumber: 871,
columnNumber: 15,
stack: 'createError#http://localhost:3000/static/js/1.chunk.js:871:15\nsettle#http://localhost:3000/static/js/1.chunk.js:1092:12\nhandleLoad#http://localhost:3000/static/js/1.chunk.js:346:13\nEventHandlerNonNull*dispatchXhrRequest#http://localhost:3000/static/js/1.chunk.js:322:5\nxhrAdapter#http://localhost:3000/static/js/1.chunk.js:301:10\ndispatchRequest#http://localhost:3000/static/js/1.chunk.js:924:10\npromise callback*request#http://localhost:3000/static/js/1.chunk.js:712:23\nforEachMethodWithData/Axios.prototype[method]#http://localhost:3000/static/js/1.chunk.js:736:17\nwrap#http://localhost:3000/static/js/1.chunk.js:1252:15\nsignUp/<#http://localhost:3000/static/js/main.chunk.js:3406:50\ncreateThunkMiddleware/</</<#http://localhost:3000/static/js/1.chunk.js:40096:18\ndispatch#http://localhost:3000/register:1:28546\nonAuth#http://localhost:3000/static/js/main.chunk.js:3305:110\nRegMain/this.handlesubmit#http://localhost:3000/static/js/main.chunk.js:2684:62\ncallCallback#http://localhost:3000/static/js/1.chunk.js:8030:18\ninvokeGuardedCallbackDev#http://localhost:3000/static/js/1.chunk.js:8079:20\ninvokeGuardedCallback#http://localhost:3000/static/js/1.chunk.js:8132:35\ninvokeGuardedCallbackAndCatchFirstError#http://localhost:3000/static/js/1.chunk.js:8147:29\nexecuteDispatch#http://localhost:3000/static/js/1.chunk.js:8232:46\nexecuteDispatchesInOrder#http://localhost:3000/static/js/1.chunk.js:8257:24\nexecuteDispatchesAndRelease#http://localhost:3000/static/js/1.chunk.js:11141:33\nexecuteDispatchesAndReleaseTopLevel#http://localhost:3000/static/js/1.chunk.js:11150:14\nforEachAccumulated#http://localhost:3000/static/js/1.chunk.js:11122:12\nrunEventsInBatch#http://localhost:3000/static/js/1.chunk.js:11167:25\nrunExtractedPluginEventsInBatch#http://localhost:3000/static/js/1.chunk.js:11377:23\nhandleTopLevel#http://localhost:3000/static/js/1.chunk.js:11421:40\nbatchedEventUpdates$1#http://localhost:3000/static/js/1.chunk.js:29567:16\nbatchedEventUpdates#http://localhost:3000/static/js/1.chunk.js:8639:16\ndispatchEventForLegacyPluginEventSystem#http://localhost:3000/static/js/1.chunk.js:11431:28\nattemptToDispatchEvent#http://localhost:3000/static/js/1.chunk.js:12151:48\ndispatchEvent#http://localhost:3000/static/js/1.chunk.js:12072:45\nunstable_runWithPriority#http://localhost:3000/static/js/1.chunk.js:41893:16\nrunWithPriority$1#http://localhost:3000/static/js/1.chunk.js:18917:14\ndiscreteUpdates$1#http://localhost:3000/static/js/1.chunk.js:29584:16\ndiscreteUpdates#http://localhost:3000/static/js/1.chunk.js:8652:16\ndispatchDiscreteEvent#http://localhost:3000/static/js/1.chunk.js:12051:22\nEventListener.handleEvent*addEventBubbleListener#http://localhost:3000/static/js/1.chunk.js:11905:15\ntrapEventForPluginEventSystem#http://localhost:3000/static/js/1.chunk.js:12045:31\ntrapBubbledEvent#http://localhost:3000/static/js/1.chunk.js:12015:36\nsetInitialProperties#http://localhost:3000/static/js/1.chunk.js:13826:27\nfinalizeInitialChildren#http://localhost:3000/static/js/1.chunk.js:15351:27\ncompleteWork#http://localhost:3000/static/js/1.chunk.js:26705:44\ncompleteUnitOfWork#http://localhost:3000/static/js/1.chunk.js:29895:20\nperformUnitOfWork#http://localhost:3000/static/js/1.chunk.js:29868:16\nworkLoopSync#http://localhost:3000/static/js/1.chunk.js:29833:26\nperformSyncWorkOnRoot#http://localhost:3000/static/js/1.chunk.js:29451:13\nscheduleUpdateOnFiber#http://localhost:3000/static/js/1.chunk.js:28883:32\nupdateContainer#http://localhost:3000/static/js/1.chunk.js:32032:19\nlegacyRenderSubtreeIntoContainer/<#http://localhost:3000/static/js/1.chunk.js:32415:26\nunbatchedUpdates#http://localhost:3000/static/js/1.chunk.js:29601:16\nlegacyRenderSubtreeIntoContainer#http://localhost:3000/static/js/1.chunk.js:32414:25\nrender#http://localhost:3000/static/js/1.chunk.js:32497:14\n./src/index.js#http://localhost:3000/static/js/main.chunk.js:4166:50\n__webpack_require__#http://localhost:3000/static/js/bundle.js:785:30\nfn#http://localhost:3000/static/js/bundle.js:151:20\n1#http://localhost:3000/static/js/main.chunk.js:4181:18\n__webpack_require__#http://localhost:3000/static/js/bundle.js:785:30\ncheckDeferredModules#http://localhost:3000/static/js/bundle.js:46:23\nwebpackJsonpCallback#http://localhost:3000/static/js/bundle.js:33:19\n#http://localhost:3000/static/js/main.chunk.js:1:71\n',
config: {
url: 'http://127.0.0.1:8000/rest-auth/register/',
method: 'post',
data: '{"fname":"Abhiram","lname":"PS","username":"rooteeee","phone":"8589967868","email":"abhirampjayan#outlook.com","cemail":"abhirampjayan#outlook.com","password1":"abhi1998","password2":"abhi1998","gender":"M","acctype":"Student"}',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8'
},
transformRequest: [
null
],
transformResponse: [
null
],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1
}
}
source code of serializer.py is given bellow
from rest_framework import serializers
from accounts.models import Account
from allauth.account import app_settings as allauth_settings
from allauth.utils import email_address_exists
from allauth.account.adapter import get_adapter
from allauth.account.utils import setup_user_email
from rest_framework.validators import UniqueValidator
from rest_framework.response import Response
from rest_framework import status
class CustomUserDetailsSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('pk','email','fname','lname','username','phone','gender','acctype')
#read_only_fields = ('email','acctype','fname','lname')
class CustomRegisterSerializer(serializers.Serializer):
fname = serializers.CharField(required=True, write_only=True)
lname = serializers.CharField(required=True, write_only=True)
username = serializers.CharField(min_length=allauth_settings.USERNAME_MIN_LENGTH,required=allauth_settings.USERNAME_REQUIRED,validators=[UniqueValidator(queryset=Account.objects.all(),message='A user is already registered with this Username.')])
phone=serializers.CharField(required=True, write_only=True,min_length=10,max_length=10)
email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
cemail = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
password1 = serializers.CharField(write_only=True, required=True)
password2 = serializers.CharField(write_only=True, required=True)
acctype=serializers.ChoiceField(['Student','Staff'])
gender=serializers.ChoiceField([('M','M'),('F','F')])
def validate_email(self, email):
email = get_adapter().clean_email(email)
if allauth_settings.UNIQUE_EMAIL:
if email and email_address_exists(email):
raise serializers.ValidationError(("A user is already registered with this e-mail address."))
return email
def validate_password1(self, password):
return get_adapter().clean_password(password)
def validate(self, data):
if data['password1'] != data['password2']:
raise serializers.ValidationError(("The password fields didn't match."))
if data['email'] !=data['cemail']:
raise serializers.ValidationError(("The email fields didn't match."))
return data
def get_cleaned_data(self):
return {
'fname': self.validated_data.get('fname', ''),
'lname': self.validated_data.get('lname', ''),
'username': self.validated_data.get('username', ''),
'acctype': self.validated_data.get('acctype', ''),
'gender': self.validated_data.get('gender', ''),
'phone': self.validated_data.get('phone', ''),
'password1': self.validated_data.get('password1', ''),
'email': self.validated_data.get('email', ''),
}
def save(self, request):
adapter = get_adapter()
user = adapter.new_user(request)
self.cleaned_data = self.get_cleaned_data()
adapter.save_user(request, user, self)
setup_user_email(request, user, [])
user.fname=self.cleaned_data.get('fname')
user.lname=self.cleaned_data.get('lname')
user.phone=self.cleaned_data.get('phone')
user.acctype=self.cleaned_data.get('acctype')
user.gender=self.cleaned_data.get('gender')
user.save()
return user
redux action creators file(auth.js) is given below
import * as actionTypes from './actionTypes'
import axios from 'axios'
export const authStart=()=>{
return{
type:actionTypes.AUTH_START
}
}
export const authSuccess=(token)=>{
return{
type:actionTypes.AUTH_SUCCESS,
token:token
}
}
export const authFail=(error)=>{
return{
type:actionTypes.AUTH_FAIL,
error:error
}
}
export const checkAuthTimeout = expirationTime =>{
return disaptch=>{
setTimeout(()=>{
disaptch(logout())
},expirationTime * 1000)
}
}
export const autLlogout=()=>{
return{
type:actionTypes.AUTH_LOGOUT
}
}
export const authLogin=(username,password)=>{
return disaptch=>{
disaptch(authStart())
axios.post('http://127.0.0.1:8000/rest-auth/login/',{
username:username,
password:password
}).then(res=>{
const token=res.data.key
const expirationDate = new Date(new Date().getTime() + 3600 * 1000)
localStorage.setItem('token',token)
localStorage.setItem('expirationDate',expirationDate)
disaptch(authSuccess(token))
disaptch(checkAuthTimeout(3600))
}).catch(err=>{
disaptch (authFail(err))
})
}
}
export const signUp=(fname,lname,username,phone,email,cemail,password1,password2,gender,acctype)=>{
return disaptch=>{
disaptch(authStart())
axios.post('http://127.0.0.1:8000/rest-auth/register/',{
fname:fname,
lname:lname,
username:username,
phone:phone,
email:email,
cemail:cemail,
password1:password1,
password2:password2,
gender:gender,
acctype:acctype,
}).then(res=>{
const token=res.data.key
const expirationDate = new Date(new Date().getTime() + 3600 * 1000)
localStorage.setItem('token',token)
localStorage.setItem('expirationDate',expirationDate)
disaptch(authSuccess(token))
disaptch(checkAuthTimeout(3600))
}).catch(err=>{
disaptch (authFail(err))
})
}
}
export const logout=()=>{
localStorage.removeItem('uesr')
localStorage.removeItem('expirationDate')
return {
type:actionTypes.AUTH_LOGOUT
}
}
export const authCheckState=()=>{
return disaptch=>{
const token=localStorage.getItem('token')
if(token===undefined){
disaptch(logout())
}else{
const expirationDate=new Date(localStorage.getItem('expirationDate'))
if(expirationDate<=new Date()){
disaptch(logout())
}else{
disaptch(authSuccess(token))
disaptch(checkAuthTimeout((expirationDate.getTime()-new Date().getTime())/1000))
}
}
}
}
On first glance, this issue looks to be in react layer:
Axios will treat the 400 status code response as an error, and rather than resolve the promise and determine response data, will throw the error you are seeing above.
One way to handle this:
axios.create({
// ...vars
responseType: "json",
validateStatus: status => {
// handling our own errors less than 500 status
return status < 500;
},
headers: headers
});
when creating the initial axios client. This will cause axios to not throw an error.
Then, within your promise .then(res=>{...}) you will need to check the response status code for 400, and process errors accordingly.
Code:
export const authLogin=(username,password)=>{
return dispatch=>{
dispatch(authStart())
axios.post('http://127.0.0.1:8000/rest-auth/login/',{
username:username,
password:password
}, {
validateStatus: status => {return status < 500}
}).then(res=>{
if (res.status === 400) {
// Will have validation errors on response body
dispatch(authFail(res.data))
} else {
const token=res.data.key
const expirationDate = new Date(new Date().getTime() + 3600 * 1000)
localStorage.setItem('token',token)
localStorage.setItem('expirationDate',expirationDate)
dispatch(authSuccess(token))
dispatch(checkAuthTimeout(3600))
}
}).catch(err=>{
dispatch (authFail(err))
})
}
}

Django can only concatenate str (not "list") to str

Django can only concatenate str (not "list") to str
Error Messages.......
I have some code like this:
function form_submit() {
var arr_category = new Array();
var arr_lawyer = new Array();
var data = new Object();
$('input[name^="category_idx"]').each(function() {
arr_category.push($(this).val());
});
$('input[name^="lawyer_idx"]').each(function() {
arr_lawyer.push($(this).val());
});
console.log("arr_category=="+arr_category);
console.log("arr_lawyer=="+arr_lawyer);
if (confirm('edit??') == true) {
data.arr_category = arr_category;
data.arr_lawyer = arr_lawyer;
call_ajax('/admin/lawyer/recommend_add', data);
//alert("arr_lawyer=="+arr_lawyer);
}
}
Am I doing well in jquery?
look at console.log
arr_category==1,2,3,4,5,6,7,8,9
arr_lawyer==64,37,57,58,130,62,38,51,110
admin_view.py
#csrf_exempt
def recommend_add(request):
print("TEST BANG VALUE------------")
if request.is_ajax() and request.method == "POST":
arr_category = request.GET.getlist('arr_category[]')
print("arr_category------------" + arr_category)
code = 0
msg = "TEST."
data = json.dumps({
'code': code,
'msg': msg,
#'retURL': retURL
})
return HttpResponse(data, content_type='application/json')
I want to print.
error message
TypeError: can only concatenate str (not "list") to str
How can I do that?
In case if you want to return a python interpreter error message to jquery's ajax call then you can use the below syntax.
def recommend_add(request):
print("TEST BANG VALUE------------")
if request.is_ajax() and request.method == "POST":
try:
arr_category = request.GET.getlist('arr_category[]')
print("arr_category------------" + arr_category)
code = 0
msg = "Success"
except Exception as e:
code = '' # anything you want as per your internal logic in case of error.
msg = str(e)
data = json.dumps({
'code': code,
'msg': msg,
#'retURL': retURL
})
return HttpResponse(data, content_type='application/json')
Please ignore my indentation.
in your print code try this
print("arr_category------------:", arr_category)

View didn't return a response

I am working on a python django web app in which I want to implement internationalization and auto translate the whole app into french or chinese.
I took reference from this site https://www.metod.io/en/blog/2015/05/05/django-i18n-part-1/
But whenever I try to run the app it shows this error:
500: ValueError at /en/get_dashboard_data/ The view
dashboard.views.getDashboardData didn't return an HttpResponse object.
It returned None instead.
And url get_dashboard_data is fetching data through ajax.
url(r'^get_dashboard_data/$', views.getDashboardData, name='getDashboardData'),
view
#login_required(login_url='/')
def getDashboardData(request):
dbname = request.user.username
if request.method == 'POST' and request.is_ajax():
if request.POST.get('action') == 'sale_chart_data':
data = DashboardData(dbname).getSaleChartData()
channel_list = data[0]
data_list = data[1]
print 123, data_list, channel_list
return HttpResponse(json.dumps({'channel_list':channel_list, 'data_list':data_list}), content_type='application/json')
if request.POST.get('action') == 'get_sale_numbers':
sale_data = DashboardData(dbname).getSaleNumbers()
return HttpResponse(json.dumps({'sale_number_data':sale_data}), content_type='application/json')
if request.POST.get('action') == 'get_inventory_numbers':
inventory_data = DashboardData(dbname).getInventoryData()
return HttpResponse(json.dumps({'inventory_data':inventory_data}), content_type='application/json')
if request.POST.get('action') == 'get_order_numbers':
order_data = DashboardData(dbname).getOrderData()
return HttpResponse(json.dumps({'order_data':order_data}), content_type='application/json')
if request.POST.get('action') == 'get_hourly_data':
order_data = DashboardData(dbname).getHourlyData()
sale_data = order_data[1]
count_data = order_data[0]
return HttpResponse(json.dumps({'sale_data':sale_data, 'count_data':count_data}), content_type='application/json')
if request.POST.get('action') == 'top_performers':
data = DashboardData(dbname).getTopPerformers()
inventory_count_dict = data[0]
current_month_dict = data[1]
last_month_dict = data[2]
current_quarter_dict = data[3]
current_year_dict = data[4]
channel_list = data[5]
return HttpResponse(json.dumps({'inventory_count_dict':inventory_count_dict,'current_month_dict':current_month_dict,'last_month_dict':last_month_dict,'current_quarter_dict':current_quarter_dict,'current_year_dict':current_year_dict,'channel_list':channel_list}), content_type='application/json')
if request.POST.get('action') == 'top_products':
product_data = DashboardData(dbname).getTopProducts()
return HttpResponse(json.dumps({'product_data':product_data}), content_type='application/json')
javascript
function getSaleChart(){
$.ajax({
url : "/get_dashboard_data/",
type : "POST",
data : {action:'sale_chart_data'},
success : function(response) {
channel_list = response.channel_list;
data_list = response.data_list;
c3.generate({
bindto: '#sale-chart-30-days',
data:{
x: 'dates',
xFormat: '%b %d',
columns: data_list,
colors:{
Flipkart: '#1AB394',
Paytm: '#BABABA'
},
type: 'bar',
groups: [ channel_list ]
},
axis: {
x: {
type: 'timeseries'
}
}
});
},
error : function(xhr,errmsg,err) {
toastr["error"]("Something Broke.", "Oops !!!.");
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
This is why you should really practice more defensive programming. Though you insist that the request method is POST and it is ajax and the action is sale_chart_data one of the three isn't what you expect it to be.
Your function really should be like follows. It's plain old good practice.
def getDashboardData(request):
dbname = request.user.username
if request.method == 'POST' and request.is_ajax():
action = request.POST.get('action')
if action == 'sale_chart_data':
data = DashboardData(dbname).getSaleChartData()
....
...
# other if conditions here
else :
return HttpResponse(json.dumps({'message':'Unknown action {0}'.format(action)}), content_type='application/json')
else :
return HttpResponse(json.dumps({'message':'Only ajax post supported'}), content_type='application/json')
And then you ought to set break points and evaluate the request to figure out what exactly is happening in this particular request.
My guess would be that your JavaScript does indeed make a POST request to /get_dashboard_data/ but it receives a redirect response (HTTP 301 or 302) to /en/get_dashboard_data/ due to some kind of i18n middleware.
The browser follows the redirect, but the new request to /en/get_dashboard_data/ is a GET request.
Edit:
When following a redirect, the browser will always perform the second request as GET, there is no way to prevent that. You have several options to solve this:
make the initial request to the right application. This means you have to pass your i18n URL into your JavaScript instead of hardcoding it. You can add something like this to your template:
<script>var dashBoardDataUrl = "{% url "name-of-dashboard-url" %}"</script>
as your "actions" just get code, you could just accept a GET request and read the action from query paramters
Split that view into several smaller views that accept GET request so you have something that resembles a REST API.