[Fixed]-How to create or register User using django-tastypie API programmatically?


When creating a user you need either use method set_password user.set_password(bundle.data.get('password')) or use a create_user method of User object.

user = User.objects.create_user(bundle.data.get('username'), bundle.data.get('email'), bundle.data.get('password'))

So something like this would work for you:

def obj_create(self, bundle, request=None, **kwargs):
        bundle = super(CreateUserResource, self).obj_create(bundle, request, **kwargs)
    except IntegrityError:
        raise BadRequest('That username already exists')
    return bundle


I was in the same situation and found both solutions helpful, but not complete. In both of them, I could create users with empty username. I didn’t want to have such leaks so here is what I did.

First, I created a validation form:

from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User

class UserForm(forms.ModelForm):
def __init__(self, *args, **kwargs): 
    super(UserForm, self).__init__(*args, **kwargs)

    self.fields['username'].error_messages = {'required': "Please enter username"}
    self.fields['username'].max_length = 30
    self.fields['password'].error_messages = {'required': 'Please enter password'}
    self.fields['password'].max_length = 30

    self.fields['email'].required = False

def clean_username(self):
    username = self.cleaned_data['username']
    if len(username) < 4:
        raise forms.ValidationError("Username has to be longer than 4 characters")  
    return username

def clean_password(self):
    password = self.cleaned_data['password']
    if len(password) < 5:
        raise forms.ValidationError("Password has to be longer than 5 characters")
    return password   

class Meta:
    model = User
    fields = ('username', 'email', 'password')

Then, inside the UserResource

validation = FormValidation(form_class=UserForm)

def obj_create(self, bundle, request=None, **kwargs):
    bundle = super(UserResource, self).obj_create(bundle, request, **kwargs)

    return bundle

I hope my solution can help fellow developers. Happy coding!


I was trying to use similar code with django-tastypie==0.9.12 and got into errors regarding missing queryset and number of arguments for obj_create. Using the following code worked for me:

from django.contrib.auth.models import User
from django.db import IntegrityError

from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from tastypie.authentication import Authentication
from tastypie import fields
from tastypie.exceptions import BadRequest

class UserSignUpResource(ModelResource):
    class Meta:
        object_class = User
        resource_name = 'register'
        fields = ['username', 'first_name', 'last_name', 'email']
        allowed_methods = ['post']
        include_resource_uri = False
        authentication = Authentication()
        authorization = Authorization()
        queryset = User.objects.all()

    def obj_create(self, bundle, request=None, **kwargs):
            bundle = super(UserSignUpResource, self).obj_create(bundle)
        except IntegrityError:
            raise BadRequest('Username already exists')

        return bundle

Some test code would be:

from django.contrib.auth.models import User
from django.contrib.auth.hashers import check_password

from tastypie.test import ResourceTestCase

class UserSignUpResourceTest(ResourceTestCase):
    def test_post_list(self):
        post_arguments = {
            "email": "youremail@example.com",
            "first_name": "John",
            "last_name": "Doe",
            "username": "test-user",
            "password": "idiotic-pwd"
        # Check how many are there
        self.assertEqual(User.objects.count(), 0)
        format='json', data=post_arguments))
        # Check how many are there. Should be one more
        self.assertEqual(User.objects.count(), 1)
        # Check attributes got saved correctly
        user = User.objects.get(username='test-user')
        for atr in post_arguments:
            if atr == 'password':
                check_password(post_arguments[atr], getattr(user, atr))
                self.assertEqual(post_arguments[atr], getattr(user, atr))

Leave a comment