How can I create an object in the Tastypie API?

I am creating a Tastypie API for my Django project. I have models in django models.py like this:

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 

and I also have a ModelResource for my Tastypie API, for example:

 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 

but it does not work. I looked. How to create or register a user using the django-tastypie programming interface? but I don’t know how to create a user in my database.

I use:

  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 

to make a POST method.

How to create an object using the Tastypie API?

+4
source share
1 answer

You cannot create a user with positional arguments like you:

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

Instead, you should use keyword arguments:

 User(nick=nick, email=" email@test ", ... ) 
+2
source

All Articles