How to fix upload file from angular 7 to django rest - django

I'have rest api devlopped with djago and application front devlopped with agular7 and i try to upload image to my rest api when i try to send it with form data the form data is empty in the api.
for angular i try to send form data with file.
Angular:
getPredictionImage(file): Observable<any> {
const HttpUploadOptions = {
headers: new HttpHeaders({ 'Content-Type': 'multipart/form-data'})
}
const f = new FormData();
f.append('image', file, file.name);
console.log(f);
return this.http.post(this.urlapiimage, file, HttpUploadOptions);
}
Django:
def post(self, request, format=None):
print("heloooo")
print(request.data)
serializer = MammographySerializer(data=request.data)
print(serializer)
if serializer.is_valid():
result='hi'
serializer.save()
return Response(result,status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
the request.data is empty

it worked for me may be this help u to find your solution
Angular :
upload(file): Observable<any> {
let csrftoken = getCookie('csrftoken');
let headers = new HttpHeaders({
'Access-Control-Allow-Origin': '*',
'X-CSRFToken': csrftoken,
});
const formdata = new FormData();
formdata.append("image", file); //i did not use 3rd argument file.name
let options = {
headers: headers, withCredentials :true }
return this.http.post(this.urlapiimage , formdata, options )
}
Django:
def post(self, request, format=None):
if 'file' not in request.data:
raise ParseError("Empty content ")
photo = request.data["file"]
serializer = MammographySerializer(photo = photo) // use this instead data =request.data
if serializer.is_valid():
result='hi'
serializer.save()
return Response(result,status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
after trying this , than also u r getting error , read about DRF parser ( https://www.django-rest-framework.org/api-guide/parsers/)
"important point if u r using chrome and if r using http://127.0.0.1:8000/ for django server and localhost:4200/ for angular than because of CORS(different ports) chrome does not allow . use this 127.0.0.1:4200/ for angular server instead of localhost:4200/ and if u don't want to do this use firefox instead of chrome it allows CORS

Related

getting code 400 message Bad request syntax , after post from flutter

getting code 400 message Bad request syntax , after post from flutter,
with postman request send and no problem but with flutter after Post Map data to Django server i get this error
[19/May/2020 14:58:13] "POST /account/login/ HTTP/1.1" 406 42
[19/May/2020 14:58:13] code 400, message Bad request syntax ('32')
[19/May/2020 14:58:13] "32" 400 -
Django
#api_view(['POST'])
def login_user(request):
print(request.data)
if request.method == 'POST':
response = request.data
username = response.get('username')
password = response.get('password')
if password is not None and username is not None:
user = authenticate(username=username, password=password)
if user is not None:
create_or_update_token = Token.objects.update_or_create(user=user)
user_token = Token.objects.get(user=user)
return Response({'type': True, 'token': user_token.key, 'username': user.username},
status=status.HTTP_200_OK)
else:
return Response({'type': False, 'message': 'User Or Password Incorrect'},
status=status.HTTP_404_NOT_FOUND)
else:
return Response({'type': False, 'message': 'wrong parameter'}, status=status.HTTP_406_NOT_ACCEPTABLE)
else:
return Response({'type': False, 'message': 'method is wrong'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
flutter
Future<dynamic> postGoa(String endpoint, Map data)async{
Map map = {
"username":"user",
"password":"password"
};
var url = _getUrl("POST", endpoint);
var client = new HttpClient();
HttpClientRequest request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.headers.set('Authorization', 'Bearer '+ athenticated
);
request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String mydata= await response.transform(utf8.decoder).join();
client.close();
return mydata;
}
}
after add
request.add(utf8.encode(json.encode(map)));
i get error in Django console
Try printing out your request headers from the Django application.
print(request.headers)
I bet one of the headers is Content-Type: ''. If that is the case, Django isn't reading your POST data because it thinks there is no data. I recommend calculating the length of the content you are sending in Flutter, then sending the correct Content-Length header with your request.
That might look something like this (in your Flutter app):
encodedData = jsonEncode(data); // jsonEncode is part of the dart:convert package
request.headers.add(HttpHeaders.contentLengthHeader, encodedData.length);

Cookies works in Postman , but not in browser

I created a login API using Django rest framework and then used session auth.
When i sent request via Postman , i get csrftoken and sessionid cookies.
and i was able to access content on backend.
OK fine.
But when i built small login form html and called that API for logging in. It worked.
I see COOKIES IN RESPONSE BUT COOKIES ARE NOT SET IN CHROME BROWSER.
Under Storage section in dev tools cookies are empty.
when i tried to access content(other views/apis) , i was not able to..
I think its because of Cookies are not being stored in browser..
Been on this like 5 days. Please can Someone explain about cookies not being saved.?
View.py
class Login(APIView):
authentication_classes = [SessionAuthentication,]
def post(self, request, format=None):
username = request.POST.get("username", "")
print(request.session)
password = request.POST.get("password", "")
user = authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
print(user)
return Response('Yes')
else :
return Response('No')
class List(APIView):
authentication_classes = [SessionAuthentication,]
permission_classes = [IsAuthenticated,]
def get(self, request, format=None):
return Response("Ark")
My Axios Request for login :
let s = this;
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
myHeaders.append("Authorization", "Basic cjox");
myHeaders.append("Access-Control-Allow-Credentials","*");
var urlencoded = new URLSearchParams();
var requestOptions = {
method: 'POST',
credentials: 'same-origin',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
axios.post("http://127.0.0.1:8000/api/login/",urlencoded,{headers:myHeaders},{withCredentials: true})
.then(res=>{
console.log(res.headers);
})
My other request :
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
myHeaders.append("Access-Control-Allow-Credentials","*");
var urlencoded = new URLSearchParams();
var requestOptions = {
method: 'GET',
credentials: 'same-origin',
headers: myHeaders,
redirect: 'follow'
};
axios.get("http://127.0.0.1:8000/api/d/",{headers:myHeaders},{withCredentials: true});

Django AJAX login without re-direct

Yes, there is a similar question without resolution to the actual question.
My users may be trying out the app and then decide to register for an account to save. Once registered I need to log them in without redirecting or reloading the page. I've got the registration working and logging them in is no problem, but what do I return to the client in order for the logged in session to be active in the browser? I'm not looking to add any other frameworks or libraries to the stack, please.
Django View (some omitted)
class CheckAuthTokenAjaxView(FormView):
form_class = AuthTokenForm
def post(self, *args, **kwargs):
form = self.form_class(self.request.POST)
u = get_user_model().objects.filter(email=email).first()
u.email_confirmed = True
u.save()
login(self.request, u)
# What should I be sending back?
return JsonResponse({"success": True}, status=200)
JS
Doc.Register.checkAuthTokenForm = function(event) {
event.preventDefault();
var form = document.getElementById('authtoken-form');
var data = new FormData(form);
d3.json('/users/ajax/checkAuthToken/', {
method: 'post',
body: data,
headers: {
// "Content-type": "charset=UTF-8",
"X-CSRFToken": Doc.CSRF,
}
})
.then(result => {
if (result.hasOwnProperty('errors')) {
// ...
} else {
// WHAT DO I DO HERE?
}
});
}

ionic 2 upload image to django rest

I am trying to upload an image from Ionic 2 app to Django-powered website through Django Rest API.
The API is working and tested through Postman but I always get HTTP 400 BAD Request error in Ionic.
Here is my code in Ionic:
openCamera(){
var options = {
sourceType: Camera.PictureSourceType.CAMERA,
destinationType: Camera.DestinationType.DATA_URL
};
Camera.getPicture(options).then((imageData) => {
this.imageName = imageData;
this.imageURL = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
this.showAlert(err);
});
}
Upload file (I am serving my Django project on my local PC with IP address 192.168.22.4):
transferData(auth){
let headers = new Headers();
headers.append('Authorization', auth);
let formData = new FormData();
formData.append('image', this.imageURL, this.imageName);
this.http.post("http://192.168.22.4/api-imageUpload", formData, {headers: headers}).subscribe(res => {
let status = res['status'];
if(status == 200){
this.showAlert( "The image was successfully uploaded!");
}else{
this.showAlert("upload error");
}
}, (err) => {
var message = "Error in uploading file " + err
this.showAlert(message);
});
}
On Django, here is my serializer:
class ImageDetailsSerializer(serializers.ModelSerializer):
image = serializers.ImageField(max_length=None, use_url=True)
class Meta:
model = ImageDetails
fields= ('image','status','category', 'user') ####status, category has default value
and views.py:
class ImageDetailsViewSet(generics.ListCreateAPIView):
queryset = ImageDetails.objects.all()
serializer_class = ImageDetailsSerializer
I am not sure if my code in uploading file is correct. I am trying to pass the data through Form data since the form works well in my API. Is this method correct? Are there any other methods to get this work?
Note: I have tried to use Transfer Cordova plugin but it is not working.
I finally solved the problem. The HTTP 400 indicates that there is a syntax error somewhere in the code and that is the encoding used in the uploaded photo. Mobile data uses base64 encoding. When sending requests, the file will then be converted to a Unicode string.
On the other hand, Django-Rest uses normal encoding for images, thus by default, it cannot support base64 image. But luckily, this plugin is already available at GitHub.
You just need to install the plugin and import it on your serializers.py:
from drf_extra_fields.fields import Base64ImageField
class ImageDetailsSerializer(serializers.ModelSerializer):
image = Base64ImageField()
class Meta:
model = ImageDetails
fields= ('image','status','category', 'user')
On Ionic side, you have to submit the actual image not the imageURL. In my case I just have to tweak my code to:
transferData(auth){
let headers = new Headers();
headers.append('Authorization', auth);
let formData = new FormData();
formData.append('category', 1);
formData.append('status', 'Y')
formData.append('image', this.imageName);
this.http.post("http://192.168.22.4/api-imageUpload", formData, {headers: headers}).subscribe(res => {
let status = res['status'];
if(status == 201){
var message = "The image was successfully uploaded!";
this.showAlert(message);
}else{
var message = "upload error";
this.showAlert(message);
}
}, (err) => {
var message = "Error in uploading file " + err;
this.showAlert(message);
});
In order to inspect what's ongoing with the request:
from rest_framework.exceptions import ValidationError
class ImageDetailsViewSet(generics.ListCreateAPIView):
queryset = ImageDetails.objects.all()
serializer_class = ImageDetailsSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if not serializer.is_valid():
print(serializer.errors) # or better use logging if it's configured
raise ValidationError(serialize.errors)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
Even without Base64 it is possible using ionic native components for file-transfer and image-picker see here: https://gist.github.com/AndreasDickow/9d5fcd2c608b4726d16dda37cc880a7b

Anonymus user Django + Angular 2

i am using django + angular 2
i am using rest_framework_jwt with a url like this
url(r'^api/api-token-auth/', obtain_jwt_token),
url(r'^api/settings/?$', views.SettingsValues.as_view()),
My view is
class SettingsValues(generics.ListAPIView):
serializer_class = SettingsSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def get_queryset(self):
queryset = Settings.objects.all()
queryset = queryset.filter(user=self.request.user.id)
print self.request.user
return queryset
My service is:
getSettings() : Promise <SettingsValues> {
return this.http.get('/api/settings', { headers: this.headers })
.toPromise()
.then(response => response.json() as SettingsValues);
}
My login is working fine, but i cannot return the settings from django..
The print inside def get_queryset shows AnonymousUser.
Any idea what i am doing wrong ?
EDIT
private headers = new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json',
});
After obtaining the token from server, you have to save it and send in the header of subsequent api calls. Something like this:
getSettings() : Promise <SettingsValues> {
this.headers.append('Authorization', 'JWT ' + token);
return this.http.get('/api/settings', { headers: this.headers })
.toPromise()
.then(response => response.json() as SettingsValues);
}
In Angular 1.x.x, i can add this to cache Authorization Header for all subsequent api calls.
$http.defaults.headers.common.Authorization = 'JWT ' + token`;
In Angular 2, I am not sure how to cache it for all but take a look at this answer