我正在努力学习像android app这样的原型/测试/学习,应该通过json / rest和django向数据库请求GET
和POST
。我为django安装了不安,GET
请求就像魅力一样。
models.py
...
class Exercise(models.Model):
name = models.TextField()
duration = models.TextField()
repeats = models.TextField()
creationtime = models.TextField()
pausetime = models.TextField()
alarmsound = models.TextField()
description = models.TextField()
type = models.TextField()
...
views.py
....
from restless.views import Endpoint
from restless.models import serialize
from restless.http import Http201, Http400
from .models import *
from restinterface.forms import ExerciseForm
class ExercisesList(Endpoint):
def get(self, request):
return serialize(Exercise.objects.all())
...
因此,对于POST请求,我实现了这个小形式:
from django import forms
from .models import *
class ExerciseForm(forms.ModelForm):
class Meta:
model = Exercise
在android方面,我正在创建一个List<NameValuePair>
,然后将其转换为UrlEncodedFormEntity
。将它发送到django似乎也可以工作,但随后在django端,HTTP 500被抛出。
class ExercisesList(Endpoint):
def get(self, request):
return serialize(Exercise.objects.all())
def post(self, request):
form = ExerciseForm(request.data)
# USED TO TEST IF SAVE ACTUALLY WORKS - and it does work!!!
exercise = form.save()
if form.is_valid():
print 'Form seems to be valid ' + form.data
exercise = form.save()
return Http201(serialize(exercise))
else:
print 'Form seems to be invalid ' + form.data
print 'invalid data'
return Http400(reason='invalid author data',
details=form.errors)
示例输出:
[06/Jun/2014 02:38:43] "GET /exercises/ HTTP/1.1" 200 220
[{'name': u'Campusboard', 'creationtime': '12', 'duration': u'no duration', 'pausetime': u'20', 'repeats': u'5', 'type': u'repeat', u'id': 1, 'alarmsound': u'default', 'description': u'this is a description'}]
[06/Jun/2014 02:38:49] "POST /exercises/ HTTP/1.1" 500 672
{u'name': u'Ringe', u'creationtime': u'12', u'duration': u'no duration', u'pausetime': u'10', u'repeats': u'23', u'type': u'repeats', u'alarmsound': u'default', u'description': u'this is a descpription'}
看起来form.is_valid()
总是评估为false。有谁知道我在做错了什么?我也有兴趣获得更多的调试输出,然后上面发布的那个。调试标志已经激活!
干杯!
修改
猜猜我会尝试使用不同的方法,并让您更新。 - 切换框架(因为我有点匆忙),使用django休息框架,这完全符合我的目的。
答案 0 :(得分:0)
我没有使用过django-restless,但看起来request.data
应该是表单提交的结果,而不是你传递给Django表单的结果。查看the code,如果您在请求中使用表单编码标头,则该属性仅被解析为适合表单实例化的字典。
我建议忽略该属性并使用标准request.POST
字典。