So lately, I have been thinking to write about what I learnt in past 5-6 months. I will force myself to write something fun and useful every once in a while, mostly related to Django for next few weeks.
I worked with
django-tastypie for last 2-3 months to implement RESTful API
for iOS applications. It involved implementation of an end point for creating
This is not something which is really documented, so here I'm sharing my experience.
In a nutshell, we need to override
obj_create method of
ModelResource and do
some validation on posted data. After few iterations I ended up with a code
which is easily maintainable with future relases of
- Check if all required fields are set in posted data.
- Check if there is an existing user with same username or email address.
- Validate posted data (e.g. password validation).
- Set password from raw password.
- Hide raw password from response.
Let's dive in.
I have created an example project on Github for user registration. It uses Django 1.5, Custom user model and django-tastypie v0.10.0.
Django 1.4.x have been used for this example.
Since, support for custom User model was not very good in
v0.9.15, I had to define
UserProfile model in
Django 1.4.x style.
Here is the code for
In case you need custom password validation
If you have some rules for passwords then it's best to have that logic in a function, because we may need to use that at different places (custom view for resetting password?).
I defined following
validate_password function which uses regular expressions:
Raising custom exception for bad http requests
Format of JSON response for bad requests changed from
django-tastypie which caused some issues for iOS application we were building.
So, I wrote following custom class to solve this:
Model resources to manage user profiles
I have defined 3 model resources as you can see in following code snippet:
UserResource- it uses
CreateUserResource- used for creating new
UserProfileResource- used to
I had to define two resources for
UserProfile model because creating new
user will be unauthenticated
POST request but
request.user for filtering. Currently there is no support for specifying
authentication for each method method.
Following steps are involved in validating posted data:
CreateUserResourceis used to check if required fields are available in
CreateUserResourceis used to check if there is any other user with same
UserResourceis used to validate
UserResourceis used to delete
You should also check if there is any other user with same
This simple implementation is easiliy maintainable. If you have any questions or suggestions please post them in comments.