$http request from AngularJS to Django - django

I am trying to send GET request to Django. In the script:
$http({
method: 'GET',
url: 'response/',
data: 'test=data',
}).success(function(data, status, headers, config){
console.log(data);
});
In the view response() function, if I try
def response(request):
data = json.loads(request.body)
return HttpResponse(data)
I will get 500 (INTERNAL SERVER ERROR). If I try
def response(request):
data = request.body
return HttpResponse(data)
the returned data is empty. I wonder what is happening?

do it like this:
$http({
method: 'GET',
url: 'response/',
data: $.param({
'test': 'data
})
}).success(function(data, status, headers, config){
console.log(data);
});
and use request.GET -
def response(request):
data = request.GET.get('test')
return HttpResponse(data)

We can use the code like this.
$http({
method: 'GET', url: '../../load/',
data: {'test': 'Nath'},
header: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (data) {
var ck = data.data;
}, function(response) { console.log("failed to load data."); });
views will be
def response(request):
data = request.GET.get('test')
return HttpResponse(data)
it worked..

Related

DJANGO not receiving data with POST

I'm having an issue trying to send data with fetch to DJANGO.
I want to send some data to django through fetch but when I debug I receive nothing in the post value, do you know what could be happening?
This is my fetch call:
const defaults = {
'method': 'POST',
'credentials': 'include',
'headers': new Headers({
'X-CSRFToken': csrf_token,
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}),
data:{'name':'A name'},
dataType:'json'
}
const response = await fetch (url, defaults)
When I debug I get an empty querydict in the request.POST
What am I doing wrong?

Using CSRF in an AJAX Call causes Uncaught TypeError: Cannot read property 'value' of null

I am struggling to figure out why my code is returning an error that is being caused by using CSRF in an Ajax call. The error is this:
Uncaught TypeError: Cannot read property 'value' of null
at HTMLUListElement.<anonymous>
Here is my AJAX Call including setup:
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
type: "POST",
url : '/api/uservenue/',
data: {
'cafeName': cafeName,
'list_id': 1,
csrfmiddlewaretoken: document.querySelector('input[name="csrfmiddlewaretoken"]').value
},
success: function(data){
console.log('User clicked: ' + data)
},
failure: function(errMsg) {
alert(errMsg);
}
});
Here is my views.py file
[...]
class UserVenue(viewsets.ModelViewSet):
serializer_class = UserVenueSerializer
queryset = UserVenue.objects.all()
#ensure_csrf_cookie
def get_queryset(self):
cafeName = self.request.GET.get('cafeName', None)
print(cafeName)
return UserVenue.objects.all()
[...]
What I've tried
My JS script is at bottom of html file.
I've tried a bunch of different edits and tweaks based on reading through documentation/SO/Reddit suggestions.
I tried using method_decorators, but this seemed to raise more errors.
I'd be grateful for any advice.
Thanks!

Posting data to DjangoRestFramework api from ajax errors with 400 bad request

I have created a post api with DjangoRestFramework but sending a post request to the API from ajax errors out with 400 bad request.
here is my ajax code:
var imgsrc = canvas.toDataURL("image/png");
var dataURL = canvas.toDataURL();
var fd = new FormData();
fd.append('screenshot', dataURL);
fd.append('source', '{{source}}');
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
processData: false,
enctype: 'multipart/form-data',
url: "/api/save_screenshots/",
data: fd,
}).done(function(o) {
console.log('saved');
alert('image saved');
});
views.py
class SocialShareAPIView(CreateAPIView):
serializer_class = SocialShareCreateSerializer
permission_classes = [AllowAny]

django rest + axios put request error 403

I've read the duplicates and nothing seems to be working. I can do the put request directly from the form in the url but I can't seem to get the axios request working.
I tried:
CSRF with Django, React+Redux using Axios
https://gist.github.com/paltman/490049a64fa4115a2cea
my view.py:
class FrequencyList(generics.ListCreateAPIView):
queryset = Frequency.objects.all()
serializer_class = FrequencySerializer
class FrequencyDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Frequency.objects.all()
serializer_class = FrequencySerializer
My axios request:
axios({
method: 'put',
url: '/f/'+id,
data: {
item: item,
},
}).then(function (response) {
this.setState({needReceipt: true});
})
.catch(function (error) {
console.log(error);
});
In my settings.py:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
}
in my webpack.config.dev.js:
const axios = require('axios');
axios.defaults.xsrfHeaderName = "X-CSRFToken";
axios.defaults.xsrfCookieName = "csrftoken";
try this
axios.put('/f/'+id, { item: item })
.then(function(response){
this.setState({needReceipt: true});
});
Reference

django rest framework multiple file upload issue "UnsupportedMediaType: Unsupported media type "application/json;charset=UTF-8"

I am doing a multiple file upload call, with files and other metadata as part of form post
Frontend post call looks like:
$http({
url: "/images/add/",
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token
},
withCredentials: true,
transformRequest: angular.identity,
enctype: 'multipart/form-data',
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
},
data : data
}).then(success, error);
On django backend it looks like:
class ImageAdd(APIView):
parser_classes = (FormParser, MultiPartParser,)
def post(self, request, format=None):
print request.FILES['files']
On request.FILES['files'] it gives me error:
"UnsupportedMediaType: Unsupported media type "application/json;charset=UTF-8"
Let me know if any more information is required