我正在閱讀Django Rest Framework上的一些內容,但是發現很難實現。有一個名爲「highscores.html」的頁面,在加載時應該向RESTful服務發出GET請求。它返回該用戶的高分列表。下面相關的代碼給出:無法訪問Django REST視圖
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'))
)
我認爲你的urls.py文件配置不正確,你可以把它放在你的問題嗎? – cziemba 2015-02-06 16:12:46
下面添加了urls文件。 – user3033194 2015-02-06 16:16:03
你正在通過ajax請求高分,但你要返回一個html模板作爲響應,而不是json。小心。 – levi 2015-02-06 16:16:35