Reputation: 151
I'm having a lot difficulty accessing the post request data sent from my Angular server. Somehow Response(data) still returns the body of my post request accurately, however I can't access the content inside to create instance of my model. Below is my code
Angular end:
let header = new HttpHeaders({
'Authorization': ' JWT ' + this.authToken,
'Content-Type': 'application/json',
});
let body = {
"var1": var1,
"var2": var2,
};
return new Promise(resolve => {
this.http.post(this.server, body, {headers: header, withCredentials: true}).subscribe(data => {
console.log(data);
resolve(data);
}, err => {
console.log(err);
});
});
Django
@api_view(['POST'])
@parser_classes((JSONParser,))
def order_processing(request):
permission_classes = (permissions.IsAuthenticated,)
data = request.data
item = Item.create(data["var1"])
item.save()
return Response(data)
and I always end up getting the error:
TypeError at /post/↵create() missing 1 required positional argument:
which I think is due to data["var1"] being unavailable. Item is my custom model.
class Item(models.Model):
# Fields
var1 = models.TextField(editable=False)
# Methods
def __str__(self):
return self.var1
def create(self, var1):
order = self.create(var1=var1)
return order
On my localhost, I tried to use httpie to request and both Querydict and request.data are empty. But then Response(data) on my deployed server is still able to return the correct body so I don't know what exactly is the problem with it.
Any help would be appreciated.
Upvotes: 0
Views: 742
Reputation: 3091
As i mentioned in the comment - your create method is not classmethod. So you can't call it like you do. Because it can be called only on a instance.
But, the create is not going to work like you'd like.
Do this instead:
item = Item.objects.create(var1=data['var1'])
This will create the item.
Also another thing:
your permission_classes
don't do anything.
Instead, import the decorator:
from rest_framework.decorators import permission_classes
And change it to:
@api_view(['POST'])
@permission_classes((permissions.IsAuthenticated,))
@parser_classes((JSONParser,))
def order_processing(request):
....
Upvotes: 1