This is my models.py:
from tastypie.utils.timezone import now
from django.contrib.auth.models import User
from django.db import models
from django.template.defaultfilters import slugify
class Link(models.Model):
user = models.ForeignKey(User)
pub_date = models.DateTimeField(default=now)
title = models.CharField(max_length=200)
slug = models.SlugField()
body = models.TextField()
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
# For automatic slug generation.
if not self.slug:
self.slug = slugify(self.title)[:50]
return super(Link, self).save(*args, **kwargs)
class OAuthConsumer(models.Model):
name = models.CharField(max_length=255)
key = models.CharField(max_length=255)
secret = models.CharField(max_length=255)
active = models.BooleanField(default=True)
class Meta:
db_table = "api_oauth_consumer"
def __unicode__(self):
return u'%s' % (self.name)
Everything works now and I get this as response to: /api/v1/links/list/?format=json
{
"meta": {
"previous": null,
"total_count": 1,
"offset": 0,
"limit": 20,
"next": null
},
"objects": [
{
"body": "http://www.youtube.com/watch?v=wqQ6BF50AT4&feature=relmfu",
"title": "Youtube",
"slug": "main-kya-karoon",
"user": "/api/v1/users/1/",
"pub_date": "2012-10-01T00:23:53",
"id": 1
}
]
}
I want to make these changes:
- Pass the username and get all the links belonging to that username.
- I am currently adding content and creating new user via django admin as while doing post I always manage to get an error. I think I might have gone wrong so any help maybe a curl one liner of creating a new user using my current api would be helpful.
Edit:
This is my new api.py(I decided to create a new UserSignUpResource):
# myapp/api.py
from django.contrib.auth.models import User
from tastypie.authorization import Authorization
from tastypie import fields
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from links.models import Link
from tastypie.serializers import Serializer
from tastypie.admin import ApiKeyInline
from tastypie.models import ApiAccess, ApiKey
from django.db import models
from tastypie.authentication import ApiKeyAuthentication
from tastypie.models import create_api_key
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'users'
excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser']
authorization = Authorization()
allowed_methods = ['post','get']
fields = ['username']
def obj_create(self, bundle, request=None, **kwargs):
try:
bundle = super(CreateUserResource, self).obj_create(bundle, request, **kwargs)
bundle.obj.set_password(bundle.data.get('password'))
bundle.obj.set_username(bundle.data.get('username'))
bundle.obj.save()
except IntegrityError:
raise BadRequest('That username already exists')
return bundle
class LinkResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
authorization = Authorization()
class Meta:
queryset = Link.objects.all()
resource_name = 'links/list'
excludes = ['id']
authorization = Authorization()
include_resource_uri = False
excludes = ['limit']
def apply_filters(self,request,applicable_filters):
base_object_list = super(LinkResource, self).apply_filters(request, applicable_filters)
query = request.META.get('HTTP_AUHTORIZATION')
if query:
qset = (
Q(api_key=query))
base_object_list = base_object_list.filter(qset).distinct()
return base_object_list
class UserSignUpResource(ModelResource):
class Meta:
object_class = User
queryset = User.objects.all()
allowed_methods = ['post']
include_resource_uri = False
resource_name = 'newuser'
excludes = ['is_active','is_staff','is_superuser']
authentication = ApiKeyAuthentication()
authorizaton = Authorization()
models.signals.post_save.connect(create_api_key, sender=User)
def obj_create(self,bundle,request=None,**kwargs):
try:
bundle = super(UserSignUpResource, self).obj_create(bundle,request,**kwargs)
bundle.obj.set_password(bundle.data.get('password'))
bundle.obj.save()
except IntegrityError:
raise BadRequest('The username already exists')
return bundle
def apply_authorization_limits(self,request,object_list):
return object_list.filter(id=request.user.id,is_superuser=True)
Now when I do this:
curl -v -X POST -d '{"username" : "puck", "password" : "123456"}' -H "Authorization: ApiKey superusername:linklist" -H "Content-Type: application/json" http://127.0.0.1:8000/api/v1/newuser
I get this a 404 error: The url doesn’t exist. I checked and rechecked and I don’t see any problem with the url.
Edit:
It was a rather dumb mistake on my part. I had forgotten to register the UserSignUpResource in urls.py.
1. Pass the username and get all the links belonging to that username
Look at filtering resources based on the api call in tastypie as explained in passing request variables in django/tastypie resources
For creating user see How to create or register User using django-tastypie API programmatically?