我正在阅读关于Django Rest Framework的一些内容,但我发现很难实现。有一个名为“highscores.html”的页面,在加载时,应该向RESTful服务发出GET请求。返回该用户的高分列表。相关代码如下:
views.py:
from gamestore.serializers import ScoreSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response
...
# display high scores
@api_view(['GET'])
def highscores(request, id):
print("INSIDE HIGH SCORES")
userobj = request.user
gameobj = Games.objects.get(pk=id)
scoreobj = Scores.objects.filter(game=gameobj, player=userobj)
if request.method == 'GET':
#print(scoreobj[0].game)
serializer = ScoreSerializer(scoreobj)
return Response(serializer.data, template_name='gamestore/highscores.html')
models.py:
from django.contrib.auth.models import User
from django.db import models
class Usertypes(models.Model):
user = models.OneToOneField(User)
usertype = models.TextField()
def __unicode__(self):
return self.user_name
class Games(models.Model):
name = models.CharField(max_length=100,unique=True)
category = models.CharField(max_length=100)
url = models.URLField()
developer = models.ForeignKey(User)
price = models.FloatField()
def __unicode__(self):
return self.name
class Scores(models.Model):
game = models.ForeignKey(Games)
player = models.ForeignKey(User)
registration_date = models.DateField(auto_now=False, auto_now_add=False)
gamestate = models.TextField(blank=True, null=True)
high_score_1 = models.PositiveIntegerField(default=0)
high_score_2 = models.PositiveIntegerField(default=0)
high_score_3 = models.PositiveIntegerField(default=0)
high_score_4 = models.PositiveIntegerField(default=0)
high_score_5 = models.PositiveIntegerField(default=0)
last_score = models.PositiveIntegerField(default=0)
def __unicode__(self):
return self.game
serializers.py:
from rest_framework import serializers
from gamestore.models import Scores
class ScoreSerializer(serializers.ModelSerializer):
class Meta:
model = Scores
fields = ('game', 'player', 'high_score_1', 'high_score_2', 'high_score_3', 'high_score_4', 'high_score_5')
highscores.html:
$(document).ready(function(){
var game = $(this);
var id = document.getElementById("gameid").value;
alert(id);
var csrftoken = getCookie('csrftoken');
$.ajax({
type : "GET",
url : "/highscores/",
data : {'id': id},
dataType : "json",
success : function(data){
console.log(data);
}
});
event.preventDefault();
});
实际上,我对整个主题感到困惑,并且无法理解如何在highscore.html文件的“highscores”视图中呈现Response。当我在服务器上运行时,我收到404 Not Found错误。 “高分”视图显然甚至没有被访问,因为服务器中没有显示“INSIDE HIGH SCORES”行。作为一个教程,我按照这篇文章https://realpython.com/blog/python/django-rest-framework-quick-start/#drf-setup看起来很简单,但我不理解很多东西,比如渲染输出,它的格式(例如JSON)等。有人可以帮忙吗?即使链接到易于理解的初学者文档也很有用。提前谢谢!
编辑:
urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
import gamestore.views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'wsdProject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$','gamestore.views.home'),
url(r'^login/','gamestore.views.login_view'),
url(r'^logout/','gamestore.views.logout_view'),
url(r'^registration/','gamestore.views.registration'),
url(r'^addgame/','gamestore.views.addgame'),
url(r'^devhome/','gamestore.views.devhome'),
url(r'^gamestats/','gamestore.views.gamestats'),
url(r'^savegamestate/','gamestore.views.savegamestate'),
url(r'^loadgamestate/','gamestore.views.loadgamestate'),
url(r'^editgame/(?P<id>\d+)/','gamestore.views.editgame'),
url(r'^delete/(?P<id>\d+)/','gamestore.views.deletegame'),
url(r'^loadgame/(?P<id>\d+)/','gamestore.views.loadgame'),
url(r'^loadhighscores/(?P<id>\d+)/','gamestore.views.loadhighscores'),
url(r'^highscores/(?P<id>\d+)/','gamestore.views.highscores'),
url(r'^gamestore/', include('gamestore.urls', namespace="gamestore")),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
)
答案 0 :(得分:2)
哦,你有这个网址规则url(r'^highscores/(?P<id>\d+)/'
。
因此,在您的ajax调用中,您的网址只有"/highscores/"
,并且您使用id
参数发送GET
,因此您的最终网址看起来像"/highscores/?id=some_id"
,这是错误。您的网址应如下"/highscores/some_id"
。你需要附加id。 "/highscores/"+id
$(document).ready(function(){
var game = $(this);
var id = document.getElementById("gameid").value;
alert(id);
var csrftoken = getCookie('csrftoken');
$.ajax({
type : "GET",
url : "/highscores/"+id,
dataType : "json",
success : function(data){
console.log(data);
}
});
event.preventDefault();
});
另外,在您看来,您发送的是html模板作为回复,应该是JSON
响应。只需删除template_name
参数即可。
return Response(serializer.data)