我正在为我的 Django 项目创建一个 Tastypie API。我在 django models.py 中有一个模型,如下所示:
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@test", password,timezone.now(),"od_test")
bundle.obj.save()
except IntegrityError:
raise BadRequest('That username already exists')
return bundle
但这不起作用。我看过如何以编程方式使用 django-tastypie API 创建或注册用户?但我不知道如何在我的数据库中创建用户。
我用:
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 创建对象?