Reputation: 936
when I make post request via XMLHttpRequest
it work very well but, when I make a get request in the django API view http://127.0.0.1:8000/create/
and I write a new text in the text box I got an error "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)"
here are my files code.
serlizers.py
the app is just like tweet app where I'm following this course
myRepo
from rest_framework import serializers
from .models import Tweet
class TweetActionsSerlizer(serializers.Serializer):
id = serializers.IntegerField()
action = serializers.CharField()
content = serializers.CharField(allow_blank=True, required=False)
def validate_action(self, value):
# lower = lower case letter.
# strip = drop spaces for example "like ".strip() = "like"
value = value.lower().strip()
if not value in ['like', 'unlike', 'retweet']:
raise serializers.ValidationError("this is not avalid action")
return value
class CreateTweeSerializers(serializers.ModelSerializer):
class Meta:
model = Tweet
fields = ['id', 'content', 'like']
# def get_likes(self, obj):
# return obj.like.count()
# this convert the array of users ids wholiekd to the number of likes
def validate_content(self, value):
if len(value) > 200:
raise serializers.ValidationError("This Tweet is too long")
return value
class TweeSerializers(serializers.ModelSerializer):
# like = serializers.SerializerMethodField(read_only=True)
# if the is no is_retweet @property function in models you will nedd this line.
# is_retweet = serializers.SerializerMethodField(read_only=True)
# content = serializers.SerializerMethodField(read_only=True)
# this will retrun the data of parents.
# http://127.0.0.1:8000/posts/ parent:{id,content,like}
parent = CreateTweeSerializers(read_only=True)
class Meta:
model = Tweet
fields = ['user', 'id', 'content', 'like',
'is_retweet', 'parent', ] # 'timestamp']
# def get_content(self, obj):
# content = obj.content
# # if th it is a retweet then its content will = the content of the parent.
# # this is to make sure that the already existed tweets will have the content of their parents.
# if obj.is_retweet:
# content = obj.parent.content
# return content
settings.py
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '6)ej64kx92vba7!6tq76^k0smwy)$t5z1m$q6@tn0gxvd58cl9'
# 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',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'social',
'rest_framework'
]
SITE_ID = 1
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',
]
LOGIN_URL = '/accounts/login/'
ROOT_URLCONF = 'vertualizor.urls'
ALLOWED_HOSTS = ['127.0.0.1', 'mydomain.com']
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'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 = 'vertualizor.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
AUTHENTICATION_BACKENDS = [
# Needed to login by username in Django admin, regardless of allauth
'django.contrib.auth.backends.ModelBackend',
# allauth specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
]
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DEFAULT_RENDERER_CLASSES = [
'rest_framework.renderers.JSONRenderer',
]
if DEBUG:
DEFAULT_RENDERER_CLASSES += [
'rest_framework.renderers.BrowsableAPIRenderer',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication'
],
'DEFAULT_RENDERER_CLASSES': DEFAULT_RENDERER_CLASSES
}
views.py
from django.shortcuts import render, redirect
from .models import Tweet
from django.utils.http import is_safe_url
from .serializers import CreateTweeSerializers, TweeSerializers, TweetActionsSerlizer
from rest_framework.response import Response
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import SessionAuthentication
# this woll make POST request work and re-render the new posts.
@api_view(["POST"])
# @authentication_classes([SessionAuthentication,MyCustomAuth])
@permission_classes([IsAuthenticated])
def post_create_view(request, *args, **kwargs):
serializer = CreateTweeSerializers(data=request.POST)
# raise_exception= if form.error reutnr error and status400
if serializer.is_valid(raise_exception=True):
serializer.save(user=request.user)
return Response(serializer.data, status=201)
return Response({}, status=400)
def home_view(request, *args, **kwards):
return render(request, 'pages/home.html', context={}, status=200)
@api_view(["GET"])
def post_view(request, postId, *args, **kwards):
qs = Tweet.objects.filter(id=postId)
if not qs.exists():
return Response({}, status=404)
return Response(TweeSerializers(qs.first()).data, status=200)
@api_view(["DELETE", 'POST'])
@permission_classes([IsAuthenticated])
def post_delete_view(request, postId, *args, **kwards):
qs = Tweet.objects.filter(id=postId)
if not qs.exists():
return Response({}, status=404)
qs = qs.filter(user=request.user)
if not qs.exists():
return Response({"message": 'you cant delete this Post'}, status=401)
obj = qs.first()
obj.delete()
return Response({'Message': "post removed"}, status=200)
@api_view(["GET"])
def posts_list_view(request, *args, **kwards):
qs = Tweet.objects.all()
serializer = TweeSerializers(qs, many=True)
return Response(serializer.data)
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def post_actions_view(request, *args, **kwards):
'''
actions = like,unlike,retweet
'''
# i dont understand how request.POST will send the id and the action type to the serlizer?
# data=request.POST was a mistake
serlizer = TweetActionsSerlizer(data=request.data)
print(request.data)
if serlizer.is_valid(raise_exception=True):
data = serlizer.validated_data
post_id = data.get('id')
action = data.get('action')
# you must serlize data to the get them.
content = data.get('content')
qs = Tweet.objects.filter(id=post_id)
if not qs.exists():
return Response({}, status=404)
obj = qs.first()
if action == 'like':
obj.like.add(request.user)
return Response(serlizer.data, status=200)
elif action == 'unlike':
obj.like.remove(request.user)
elif action == 'retweet':
newTwee = Tweet.objects.create(
user=request.user, parent=obj, content=content)
serlizer = TweeSerializers(newTwee)
return Response(serlizer.data, status=201)
return Response({}, status=200)
Upvotes: 0
Views: 7032
Reputation: 11808
I figured out what was your problem is :)
What I did (leads to "JSON parse error - Expecting value: line 1 column 1 (char 0)" msg on your screen) or you can repeat the same via curl or Postman:
Ok why is it wrong? - In view request.data have parsed like {"somestring"}
but it should looks like {"content": "somestring"}
So how it is correct (here I've used token authentication https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication)
Request
POST http://127.0.0.1:8000/create/
Accept: application/json
Content-Type: application/json
Authorization: Token e6f2fdd681d0b023a73cb06e9720867adeb96daf
{"content": "a"}
Response
{
"id": 10,
"content": "a",
"like": []
}
Response code: 201 (Created); Time: 50ms; Content length: 33 bytes
Upvotes: 3