Как POST и PUT данные с помощью fetch api?
Ниже представлен html-файл со всеми следующими элементами в <script
.
Он получает значение game_title, получая id элемента input, который заполняется в форме. Он правильно получает информацию, которую пользователь вводит в формы
Ниже приведен файл api.py Методы GET и DELETE работают совершенно нормально. В методе POST я пытаюсь добавить новую игру. В методе PUT я пытаюсь отредактировать конкретную игру
from django.http import JsonResponse
from django.http.response import HttpResponseBadRequest
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
import json
from .models import Game
def games_api(request):
'''
API entry point for list of games
'''
if request.method == "GET":
return JsonResponse({
'games': [
game.to_dict()
for game in Game.objects.all()
]
})
if request.method == "POST":
games = Game.objects.all()
POST = json.loads(request.body)
game = get_object_or_404(Game)
game.game_title = POST['Title']
game.age_rating = POST['AgeRating']
game.genre = POST['Genre']
game.game_release_date = POST['ReleaseDate']
game.save()
games = game.add()
return JsonResponse({})
return HttpResponseBadRequest("Invalid method")
def game_api(request,game_id):
'''
API entry point for each game
'''
if request.method == "DELETE":
game = get_object_or_404(Game, id=game_id)
game.delete()
return JsonResponse({})
if request.method == "PUT":
game = get_object_or_404(Game, id=game_id)
PUT = json.loads(request.body)
game.game_title = PUT['Title']
game.age_rating = PUT['AgeRating']
game.genre = PUT['Genre']
game.game_release_date = PUT['ReleaseDate']
game.save()
return JsonResponse({})
return HttpResponseBadRequest("Invalid method")