Reputation: 115
I'm trying to create Club
object via React form but I get those 2 errors:
{"detail": "Authentication credentials were not provided."}
and 401 Unauthorized
. Obviously there is something wrong with authorisation, I tested it with postman and it did not work, however when I tried with http://127.0.0.1:8000/api/clubs/
everything worked. I am pasting all of my code below.
frontend/CreateClub.js
import React, {useEffect, useState} from 'react';
import { useNavigate } from 'react-router-dom';
import Base from '../base/Base';
import { isAuthenticated } from '../user/helper/userApiCalls';
import { getAllClubs, createClub } from './helper/apiHelper';
const CreateClub = () => {
const [clubName, setClubName] = useState('');
const [clubs, setClubs] = useState([]);
const [nameTaken, setNameTaken] = useState(false);
const navigate = useNavigate();
useEffect(() =>{
if (!isAuthenticated()) {
navigate('/login')
} else {
loadClubs();
}
},[])
const loadClubs = () => {
getAllClubs()
.then((data) => {
setClubs(data);
})
.catch((error) => console.log(error));
}
const handleChange = (event) => {
setClubName(event.target.value)
}
const onSubmit = (event) => {
event.preventDefault();
if (checkExistingClubNames(clubName, clubs)) {
const owner = isAuthenticated().user;
const name = clubName;
createClub({owner, name})
.then((data) => {
if (data.name === clubName) {
setClubName('');
setNameTaken(false);
navigate('/');
}
})
.catch((error) => console.log(error));
} else {
setNameTaken(true);
}
}
const checkExistingClubNames = (newClubsName, existingClubs) => {
const filteredClubs = existingClubs.filter(function(existingClub) {
return existingClub.name === newClubsName
})
if (filteredClubs.length > 0) {
return false;
} else {
return true;
};
};
const createClubForm = () => {
return (
<div>
<h2>Create Club:</h2><hr/>
<form>
<div>
<label>Name</label>
<input
name="clubName"
value={clubName}
onChange={handleChange}
type="name"
/>
</div>
<button
onClick={onSubmit}
>
Submit
</button>
</form>
</div>
)
}
return (
<Base title="Create Club">
{loading && <h1>Loading...</h1>}
{!loading && createClubForm()}
{nameTaken && <p>Name taken</p>}
</Base>
);
}
export default CreateClub;
apiHelper.js
export const getAllClubs = () => {
return (
fetch('http://127.0.0.1:8000/api/clubs/', {method:"GET"})
.then((response) => {
return response.json();
})
.catch((error) => console.log(error))
)
};
export const createClub = (club) => {
return fetch('http://127.0.0.1:8000/api/clubs/', {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(club),
})
.then((response) => {
return response.json();
})
.catch((error) => console.log(error));
};
frontend/userApiCalls.js
export const isAuthenticated = () => {
if (typeof window == undefined) {
return false;
}
if (localStorage.getItem("jwt")) {
return JSON.parse(localStorage.getItem('jwt'))
} else {
return false;
}
};
game/models.py
from django.db import models
from django.conf import settings
class Club(models.Model):
name = models.CharField(max_length=25)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
backend/serializers.py
from rest_framework import serializers
from .models import Club
class ClubSerializer(serializers.ModelSerializer):
class Meta:
model = Club
fields = 'id', 'owner', 'name'
backend/views.py
from rest_framework import viewsets
from .models import Club
from .serializers import ClubSerializer
class ClubViewSet(viewsets.ModelViewSet):
queryset = Club.objects.all()
serializer_class = ClubSerializer
backend/game/urls.py
from rest_framework import routers
from django.urls import path, include
from .views import GameViewSet
router = routers.DefaultRouter()
router.register(r'clubs', ClubViewSet, basename="clubs")
urlpatterns = [
path('', include(router.urls)),
]
backend/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include("game.urls")),
path('api/accounts/', include("accounts.urls")),
path('api-auth/', include('rest_framework.urls'))
]
There's a lot of code, but to be honest I have no idea what to do next and I hope you can help me :/
Upvotes: 1
Views: 2511
Reputation: 11
if in your settings.py file you have the following syntax remove them help me to work fine
'AUTH_HEADER_TYPES': ('Bearer',),
'AUTH_HEADER_NAME': 'AUTHORIZATION',
Upvotes: 1