我正在爲我的Django項目創建一個Tastypie API。我有在Django一個型號的models.py這樣的:如何在Tastypie API中創建對象?
class User(models.Model):
nick = models.CharField(max_length = 255)
email = models.CharField(max_length = 511)
password = models.CharField(max_length = 63)
reg_date = models.DateTimeField('register date')
od_user = models.CharField(max_length = 1024)
def __unicode__(self):
aux = self.nick + " " + self.email
return aux
,我也有一個像這樣爲我Tastypie API一個ModelResource:
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
excludes = ['password']
allowed_methods = ['get', 'post', 'put', 'delete']
authorization = Authorization()
always_return_data=True
def obj_create(self, bundle, request=None, **kwargs):
username, password = bundle.data['nick'], bundle.data['password']
try:
bundle.obj = User(nick, "[email protected]", password,timezone.now(),"od_test")
bundle.obj.save()
except IntegrityError:
raise BadRequest('That username already exists')
return bundle
但這不起作用。我看過How to create or register User using django-tastypie API programmatically?,但我不知道如何在我的數據庫中創建用戶。
我用:
curl -v -H "Content-Type: application/json" -X POST --data '{"nick":"test2", "password":"alparch"}' http://127.0.0.1:8000/api/v1/user/?format=json
做POST方法。
如何使用Tastypie API創建對象?
如何在不工作?當你發佈會發生什麼?有錯誤嗎? – 2012-08-16 11:23:23
錯誤是:「error_message」:「int()的無效字面值爲10:'test2'test2是我發佈的暱稱 – 2012-08-16 11:34:26
您應該考慮使用'django.contrib.auth'中包含的'User'模型。通過編寫自己的代碼,你失去了一些功能 - 例如你正在存儲一個未加密的密碼,這是不安全的。 – Alasdair 2012-08-16 11:45:49