Django REST Framework Delete Method Request receives Forbidden 403 - django

views.py
class DeviceView(viewsets.ModelViewSet):
serializer_class = DevicesSerializer
queryset = Devices.objects.all()
permission_classes = [permissions.IsAuthenticated]
Axios Request
axios.delete(`api/devices/${data.id}/`, {}, {
headers: {'X-CSRFToken': csrftoken }
})
.then((response) => {
console.log(response);
}).catch((error) => {
console.log(error);
});
When I carry out this request on my front-end, I get a response of :"DELETE http://localhost:3000/api/devices/4/ 403 (Forbidden)". Where 4 is the ID belonging to the record I would like to delete.
I am currently using Session Authentication in Django and I have passed in my CSRF Token value into the header of my request.
When I use other methods like PUT and POST on forms, they work fine. But, not DELETE
What am I doing wrong to receive this error?

Turns out I just needed to remove the empty body in the Axios request.
axios.delete(`api/devices/${data.id}/`, {
headers: {'X-CSRFToken': csrftoken }
})
.then((response) => {
console.log(response);
}).catch((error) => {
console.log(error);
});

Related

Axios giving 401 (Unauthorized). I am trying to get userdata through react frontend passed to DRF Social Oauth2. Same working on POSTMAN

Below are the two files LoginScreen.JS which has a submit handler that submits the input. Here we import the axios instance from login.JS. I have also attached the same working example from PostMan.
login.js
const baseURL='http://127.0.0.1:8000/';
const axiosInstance = axios.create({
baseURL: baseURL,
timeout: 5000,
headers: {
'Content-Type': 'application/json',
accept: 'application/json'
},
});
export default axiosInstance
LoginScreen.js
const submitHandler = (e) => {
e.preventDefault()
axiosInstance
.post(`auth/token/`,{
username: email,
password: password,
grant_type: 'password',
client_id: 'Vqvt1yp2HahF8KgwOS3BrWaCUX8ViDGCrn3VfJkz',
client_secret: 'Vqvt1yp2HahF8KgwOS3BrWaCUX8ViDGCrn3VfJkz'
})
.then((res) => {
localStorage.setItem('access_token', res.data.access);
localStorage.setItem('refresh_token', res.data.refresh);
});
};

Django create/update multiple models in one rest request

I have a form in Vue which takes in data that is spread into multiple models when sent to django .
Rest JSON is
data = {
people:{
name: "MyName",
age: 34
},
classes:{
name:"Valgris",
tag:3492,
comment:"gob gdjoisu is tsutsi"
}
}
-THE MODELS FIELD IN DJANGO ARE
class Classes(models.Model):
name = models.CharField(_ max_length=50)
age = models.IntegerField()
class People(models.Model):
name = models.CharField(_ max_length=50)
tag = models.IntegerField()
comment= models.TextField()
--- I tried tried using perform_create in my view, and also use create in serializer but I am unable to do it. request.data does not seem to like me popping out data and saving the result. It just doesn't work well.
Is there a way out. or do I have to send two request to create People and Classes model
I think you have to use two request for your purpose.
As serializer of django-rest-framework requires your request.data as an argument,
yourSerializer(yourModel, data=request.data)
so it will not operate with the data of two models that you are sending from vue.
Also, If you want to do these API calls with one another then you can call other API inside the first one API's response.
axios
.post("first/API/call/url", dataModel1, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((response) => {
console.log(response);
axios
.post("second/API/call/url", dataModel2, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
})
.catch((error) => {
console.log(error);
});
Note: popping out data and changing it is fine for one model but for two model it's not fine.

DRF post method working without csrf token. Is it safe?

Before working with drf, i knew that, we need to add csrf token to submit the form data.
But in django-rest-framework POST method working without csrf token.
Is it safe?
createGroup=()=>{
let store = JSON.parse(localStorage.getItem('login'))
var url = 'http://127.0.0.1:8000/myapi/creategroup/'
fetch(url,{
method:'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token '+store.token,
},
body:JSON.stringify({
'name':this.state.groupName,
})
})
.then((response)=>{
response.json()
document.getElementById('i').value=''
this.setState({groupName:''})
})
}

Get UID and token obtain from password reset in react form

I am working on password reset and I have used django rest-auth, I have successfully got the token and uid from email link by hitting rest-auth/password/reset/,
but for to confirm I want the token and uid in react form so I can change it how can I get the uid and token which the rest auth return in email link in react js form
axios.post('http://127.0.0.1:8000/rest-auth/password/reset/',payload)
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(err)
})
its working perfect and it returns me:
http://127.0.0.1:8000/rest-auth/password/reset/confirm/MQ/594-5faaa46be4277e6a1879/
how can I get the uid and token from url in react form?
You should configure your react router to get the params from url.
e.preventDefault();
fetch("http://127.0.0.1:8000/rest-auth/password/reset/confirm/", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}, body: JSON.stringify({
"new_password1": this.state.new_password1,
"new_password2": this.state.new_password2,
"uid": this.props.match.params.uid,
"token": this.props.match.params.token,
})
})
// .then(response => response.json())
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})

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