无法访问 Django REST 视图
Unable to access Django REST view
我正在阅读有关 Django Rest Framework 的一些资料,但发现它很难实施。有一个名为 "highscores.html" 的页面,加载后,应该向 RESTful 服务发出 GET 请求。 which returns 该用户的高分列表。相关代码如下:
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" 视图中呈现响应。当我 运行 使用服务器时,我收到 404 Not Found 错误。 "highscores" 视图显然甚至没有被访问,因为 "INSIDE HIGH SCORES" 行没有显示在服务器中。作为教程,我遵循了这篇文章,https://realpython.com/blog/python/django-rest-framework-quick-start/#drf-setup 这看起来很简单,但我不明白很多事情,比如渲染输出、它的格式(例如 JSON)等。有人可以帮忙吗?即使是 link 一个易于理解的初学者文档也会很有用。提前致谢!
编辑:
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'))
)
好的,你有这个 url 规则 url(r'^highscores/(?P<id>\d+)/'
。
所以在你的 ajax 调用中,你的 url 只是 "/highscores/"
并且你正在使用 GET
参数发送 id
,所以你的最终 urls 看起来像 "/highscores/?id=some_id"
,这是错误的。您的 url 应该看起来像这样 "/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)
我正在阅读有关 Django Rest Framework 的一些资料,但发现它很难实施。有一个名为 "highscores.html" 的页面,加载后,应该向 RESTful 服务发出 GET 请求。 which returns 该用户的高分列表。相关代码如下:
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" 视图中呈现响应。当我 运行 使用服务器时,我收到 404 Not Found 错误。 "highscores" 视图显然甚至没有被访问,因为 "INSIDE HIGH SCORES" 行没有显示在服务器中。作为教程,我遵循了这篇文章,https://realpython.com/blog/python/django-rest-framework-quick-start/#drf-setup 这看起来很简单,但我不明白很多事情,比如渲染输出、它的格式(例如 JSON)等。有人可以帮忙吗?即使是 link 一个易于理解的初学者文档也会很有用。提前致谢!
编辑:
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'))
)
好的,你有这个 url 规则 url(r'^highscores/(?P<id>\d+)/'
。
所以在你的 ajax 调用中,你的 url 只是 "/highscores/"
并且你正在使用 GET
参数发送 id
,所以你的最终 urls 看起来像 "/highscores/?id=some_id"
,这是错误的。您的 url 应该看起来像这样 "/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)