I just started using django rest framework. I tested a single view function and it worked.
@api_view(['GET', ])
def test_api(request):
if request.method == 'GET':
data = {}
data['response'] = 'Test!'
return Response(data=data)
after that I tested registration view and in it worked too.
@api_view(['POST', ])
def doctor_registration_view(request):
if request.method == 'POST':
serializer = DoctorRegistrationSerializer(data=request.data)
data = {}
if serializer.is_valid():
doctor = serializer.save()
data['response'] = 'successfully registered.'
data['email'] = doctor.user.email
data['first_name'] = doctor.user.first_name
data['last_name'] = doctor.user.last_name
data['phone_number'] = doctor.user.phone_number
data['social_id'] = doctor.user.social_id
data['mc_code'] = doctor.mc_code
token = Token.objects.get(user=doctor.user).key
data['token'] = token
else:
data = serializer.errors
return Response(data)
class RegistrationSerializer(serializers.ModelSerializer):
password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)
class Meta:
model = User
fields = ['email', 'first_name', 'last_name', 'phone_number', 'social_id', 'password', 'password2']
extra_kwargs = {
'password': {'write_only': True}
}
def save(self):
user = User(
email=self.validated_data['email'],
first_name = self.validated_data['first_name'],
last_name=self.validated_data['last_name'],
phone_number=self.validated_data['phone_number'],
social_id=self.validated_data['social_id'],
)
password = self.validated_data['password']
password2 = self.validated_data['password2']
if password != password2:
raise serializers.ValidationError({'password': 'Passwords do not match.'})
user.set_password(password)
user.save()
return user
after this I tested token authenication for logging in with obtain_auth_token
view
urlpatterns = [
path('test/', test_api, name='test-api'),
path('register', registration_view, name='register'),
path('login', obtain_auth_token, name='login'),
]
Now when I request for test_api
it says
{"detail": "Authentication credentials were not provided."}
While I did not use @permission_classes((IsAuthenticated,))
for view functions, I don't know why test_api
wants auth token
setting.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users.apps.UsersConfig',
'api.apps.ApiConfig',
'rest_framework',
'rest_framework.authtoken',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
AUTH_USER_MODEL = 'users.User' # change the built-in user model
every other thing is default.
test_api is asking for authentication credentials because you have defined default permission classes in your settings.py.
It automatically gets applied to all the views if nothing specified. So, either you can make the DEFAULT_PERMISSION_CLASSES blank in settings.py like this:
or
you can explicitly define permission_classes for all your view functions. You can do that using