Home > Net >  My Get Api isn't working , I can't retrieve list from db as i inteded(Django)
My Get Api isn't working , I can't retrieve list from db as i inteded(Django)

Time:10-28

This is the information in my db

This is my model

Serializers

@api_view(['GET', 'POST', 'DELETE'])

def student_list(request):
if request.method == 'GET':
    student = Student.objects.all()
    FirstName = request.GET.get('FirstName', None)
    if FirstName is not None:
        student = student.filter(FirstName__icontains=FirstName)
    
    student_serializer = StudentSerializer(student, many=True)

    return JsonResponse(student_serializer.data, safe=False)
elif request.method == 'POST':
    student_data = JSONParser().parse(request)
    student_serializer = StudentSerializer(data=student_data)
    if student_serializer.is_valid():
        student_serializer.save()
        return JsonResponse(student_serializer.data, status=status.HTTP_201_CREATED) 
    return JsonResponse(student_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Above is my view, I have no problem with Post but when I use Get I only got a "[ ]" . I'm not sure where exactly is the mistake ...

PostMan Get

I was following this guide for anyone wondering : https://www.bezkoder.com/django-postgresql-crud-rest-framework/

   import os
import environ
env = environ.Env()
environ.Env.read_env()
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))
SECRET_KEY = env("SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'blog',
    'blog.apps',
]

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',
]

ROOT_URLCONF = 'ManatalAssesment.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ManatalAssesment.wsgi.application'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': env("DB_NAME"),
        'USER': env("DB_USER"),
        'PASSWORD': env("DB_PASSWORD"),
        'HOST': env("DB_HOST"),
        'PORT': env("DB_PORT"),
    }
}
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = False
STATIC_URL = '/static/'

above is my setting.py for the main project

 from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),

]

above is my project level urls

below is my app urls

    from django.urls import path
from .views import *


urlpatterns = [
      path('api/students', student_list),
#     path('api/tutorials/(?P<pk>[0-9] )$', tutorial_detail),
#     path('api/tutorials/published$', tutorial_list_published)
]

CodePudding user response:

Try removing this portion of code:-

    if FirstName is not None:
        student = student.filter(FirstName__icontains=FirstName)

You are sending the request, without FirstName I guess, and then you are filtering the queryset.

CodePudding user response:

Sorry for the bother everyone! I found out the reason for this now, and it's that I haven't install and declared the Cors header yet. So for anyone in the future don't forget to do that!

just follow the detail on this site: https://www.bezkoder.com/django-postgresql-crud-rest-framework/

  • Related