I was creating Login functionality for my Python Django backend, “create user” functionality was working fine before. But then after Login was entirely coded, the create-user stopped working.
My urls.py file:
JavaScript
x
11
11
1
from django.urls import path
2
from .views import TestView, UserView, UserLoginView
3
from rest_framework_jwt.views import refresh_jwt_token, verify_jwt_token
4
5
urlpatterns = [
6
path('test', TestView.as_view()),
7
path('create-user/', UserView.as_view()),
8
path('get-user', UserLoginView.as_view()),
9
path('login-user/', UserLoginView.as_view()),
10
]
11
My views.py file:
JavaScript
1
65
65
1
from rest_framework.views import APIView
2
from rest_framework.response import Response
3
from .serializers import UserSerializer
4
from django.contrib.auth.models import User
5
from django.contrib.auth import authenticate
6
7
8
class TestView(APIView):
9
def get(self, request, format=None):
10
print("API called")
11
return Response("You did it!", status=200)
12
13
14
class UserView(APIView):
15
def post(self, request, format=None):
16
print("Creating User")
17
18
user_data = request.data
19
print(request.data)
20
21
user_serializer = UserSerializer(data=user_data)
22
23
if user_serializer.is_valid(raise_exception=False):
24
user_serializer.save()
25
return Response({'user': user_serializer.data}, status=200)
26
27
return Response({'msg': "error: no user created"}, status=400)
28
29
30
class UserLoginView(APIView):
31
32
# convert user token to user data
33
34
def get(self, request, format=None):
35
36
if request.user.is_authenticated == False or request.user.is_active == False:
37
return Response('Invalid credentials', status=403)
38
39
user = UserSerializer(request.user)
40
print(user.data)
41
42
return Response("Testing", status=200)
43
44
def post(self, request, format=None):
45
print("Login class")
46
47
# Looking for user's email or username
48
user_obj = User.objects.filter(email=request.data['email']).first(
49
) or User.objects.filter(username=request.data['username']).first()
50
51
# if user is valid, returns user data in credentials
52
if user_obj is not None:
53
credentials = {
54
'username': user_obj.username,
55
'password': request.data['password']
56
}
57
user = authenticate(**credentials)
58
59
# if user is valid and active, logs user in
60
if user and user.is_active:
61
user_serializer = UserSerializer(user)
62
return Response("Login successful", user_serializer.data, status=200)
63
64
return Response("Invalid credentials", status=403)
65
My serializers.py file:
JavaScript
1
64
64
1
from rest_framework import serializers
2
from django.contrib.auth.models import User
3
from rest_framework.validators import UniqueValidator
4
from rest_framework_jwt.settings import api_settings
5
6
7
class UserSerializer(serializers.ModelSerializer):
8
9
token = serializers.SerializerMethodField()
10
11
email = serializers.EmailField(
12
required=True,
13
validators=[UniqueValidator(queryset=User.objects.all())]
14
)
15
16
username = serializers.CharField(
17
required=True,
18
max_length=32,
19
validators=[UniqueValidator(queryset=User.objects.all())]
20
)
21
22
first_name = serializers.CharField(
23
required=True,
24
max_length=32
25
)
26
27
last_name = serializers.CharField(
28
required=True,
29
max_length=32
30
)
31
32
password = serializers.CharField(
33
required=True,
34
min_length=8,
35
write_only=True
36
)
37
38
def create(self, validated_data):
39
password = validated_data.pop('password', None)
40
instance = self.Meta.model(**validated_data)
41
if password is not None:
42
instance.set_password(password)
43
instance.save()
44
return instance
45
46
def get_token(self, obj):
47
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
48
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
49
payload = jwt_payload_handler(obj)
50
token = jwt_encode_handler(payload)
51
return token
52
53
class Meta:
54
model = User
55
fields = (
56
'token',
57
'username',
58
'password',
59
'first_name',
60
'last_name',
61
'email',
62
'id'
63
)
64
My project’s settings.py file:
JavaScript
1
149
149
1
"""
2
Django settings for AIOHA_backend project.
3
4
Generated by 'django-admin startproject' using Django 4.0.3.
5
6
For more information on this file, see
7
https://docs.djangoproject.com/en/4.0/topics/settings/
8
9
For the full list of settings and their values, see
10
https://docs.djangoproject.com/en/4.0/ref/settings/
11
"""
12
13
from pathlib import Path
14
import datetime
15
16
# Build paths inside the project like this: BASE_DIR / 'subdir'.
17
BASE_DIR = Path(__file__).resolve().parent.parent
18
19
20
# Quick-start development settings - unsuitable for production
21
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
22
23
# SECURITY WARNING: keep the secret key used in production secret!
24
SECRET_KEY = 'django-insecure-8dz4fx@zy9&parzic^-v5%*r^w^fncmjtd2my1b)(c-e0bgs8^'
25
26
# SECURITY WARNING: don't run with debug turned on in production!
27
DEBUG = True
28
29
ALLOWED_HOSTS = ['localhost']
30
31
32
# Application definition
33
34
INSTALLED_APPS = [
35
'django.contrib.admin',
36
'django.contrib.auth',
37
'django.contrib.contenttypes',
38
'django.contrib.sessions',
39
'django.contrib.messages',
40
'django.contrib.staticfiles',
41
'rest_framework',
42
'corsheaders',
43
'userAPI',
44
]
45
46
MIDDLEWARE = [
47
'django.middleware.security.SecurityMiddleware',
48
'django.contrib.sessions.middleware.SessionMiddleware',
49
'django.middleware.common.CommonMiddleware',
50
'django.middleware.csrf.CsrfViewMiddleware',
51
'django.contrib.auth.middleware.AuthenticationMiddleware',
52
'django.contrib.messages.middleware.MessageMiddleware',
53
'django.middleware.clickjacking.XFrameOptionsMiddleware',
54
'corsheaders.middleware.CorsMiddleware',
55
]
56
57
ROOT_URLCONF = 'AIOHA_backend.urls'
58
59
TEMPLATES = [
60
{
61
'BACKEND': 'django.template.backends.django.DjangoTemplates',
62
'DIRS': [],
63
'APP_DIRS': True,
64
'OPTIONS': {
65
'context_processors': [
66
'django.template.context_processors.debug',
67
'django.template.context_processors.request',
68
'django.contrib.auth.context_processors.auth',
69
'django.contrib.messages.context_processors.messages',
70
],
71
},
72
},
73
]
74
75
WSGI_APPLICATION = 'AIOHA_backend.wsgi.application'
76
77
78
# Database
79
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
80
81
DATABASES = {
82
'default': {
83
'ENGINE': 'django.db.backends.sqlite3',
84
'NAME': BASE_DIR / 'db.sqlite3',
85
}
86
}
87
88
89
# Password validation
90
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
91
92
AUTH_PASSWORD_VALIDATORS = [
93
{
94
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
95
},
96
{
97
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
98
},
99
{
100
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
101
},
102
{
103
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
104
},
105
]
106
107
108
# Internationalization
109
# https://docs.djangoproject.com/en/4.0/topics/i18n/
110
111
LANGUAGE_CODE = 'en-us'
112
113
TIME_ZONE = 'UTC'
114
115
USE_I18N = True
116
117
USE_TZ = True
118
119
120
# Static files (CSS, JavaScript, Images)
121
# https://docs.djangoproject.com/en/4.0/howto/static-files/
122
123
STATIC_URL = 'static/'
124
125
# Default primary key field type
126
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
127
128
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
129
130
REST_FRAMEWORK = {
131
'DEFAULT_PERMISSION_CLASSES': (
132
'rest_framework.permissions.AllowAny',
133
'rest_framework.permissions.IsAuthenticated',
134
),
135
'DEFAULT_AUTHENTICATION_CLASSES': (
136
'rest_framework.authentication.SessionAuthentication',
137
'rest_framework.authentication.BasicAuthentication',
138
'rest_framework_simplejwt.authentication.JWTAuthentication',
139
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
140
),
141
}
142
143
JWT_AUTH = {
144
# how long the original token is valid for
145
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=3),
146
# allow refreshing of tokens
147
'JWT_ALLOW_REFRESH': True,
148
}
149
Postman Request:
I get the same for when I tried to log in an existing user, after which I tried creating a new one, thinking I had forgotten the password.
Command Line looks like this:
What am I missing or doing wrong? Please guide!
Advertisement
Answer
You need to add permission_classes
in UserView
. It should contain AllowAny
so that the api without authentication is allowed.
JavaScript
1
8
1
from rest_framework.permissions import AllowAny
2
3
class UserView(APIView):
4
permission_classes = [AllowAny]
5
6
def post(self, request, format=None):
7
8