我正在努力嘗試一些原型/測試/學習像android應用程序,這應該是GET
和POST
通過json/rest和django請求數據庫。我爲django安裝了不安,GET
請求像魅力一樣工作。爲什麼form.is_valid()在POST請求上評估false
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()
總是判斷爲假。有人知道我在這裏做錯了嗎?我還希望獲得更多的調試輸出,然後是上面發佈的那個。調試標誌已經激活!
乾杯!
編輯
想我會嘗試使用不同的方法,並讓你更新。 - 轉換框架(因爲我有點匆忙),使用django rest框架,這是完美的爲我的目的工作。
你嘗試使用'request.POST'而不是'ExerciseForm(request.data)'嗎? –
我確實嘗試過,但由於框架文檔使用request.data,因此我更專注於使其工作。當然,我可以使用request.POST - 我甚至會得到一個querydict,但是這會讓不安的框架無用嗎? – maiksensi