如何在Tastypie API中创建对象?

时间:2012-08-16 11:16:34

标签: django api post tastypie

我正在为我的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

但这不起作用。我看了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创建对象?

1 个答案:

答案 0 :(得分:2)

您无法以您拥有的方式创建具有位置参数的用户:

User(nick, "email@test", password,timezone.now(),"od_test")

相反,您必须使用关键字参数:

User(nick=nick,
     email="email@test",
     ...
     )