got campaign information relevant to the logged in user to show up

pull/1/head
Ed Summers 2011-09-16 00:51:46 -04:00
parent b7be628de2
commit 5246429db3
2 changed files with 53 additions and 1 deletions

View File

@ -1,6 +1,7 @@
import logging
from django.contrib.auth.models import User
from django.contrib import auth
from django.contrib.auth.models import User, AnonymousUser
from django.conf.urls.defaults import url
from django.db.models import Q
@ -42,6 +43,27 @@ class WorkResource(ModelResource):
class CampaignResource(ModelResource):
work = fields.ToOneField(WorkResource, 'work')
def alter_list_data_to_serialize(self, request, data):
"""
annotate the list of campaigns with information from the logged in
user. note: this isn't the user identified by the api username/api_key
it's the the user that client might be logged into unglue.it as.
"""
u = auth.get_user(request)
if isinstance(u, User):
data['meta']['logged_in_username'] = u.username
wishlist_work_ids = [w.id for w in u.wishlist.works.all()]
else:
data['meta']['logged_in_username'] = None
wishlist_work_ids = []
for o in data['objects']:
o.data['in_wishlist'] = o.obj.id in wishlist_work_ids
# TODO: add pledging information
return data
class Meta:
authentication = ApiKeyAuthentication()
queryset = models.Campaign.objects.all()

View File

@ -63,3 +63,33 @@ class ApiTests(TestCase):
j = json.loads(r.content)
self.assertEqual(len(j['objects']), 1)
self.assertEqual(j['objects'][0]['name'], 'Neuromancer')
self.assertEqual(j['meta']['logged_in_username'], None)
self.assertEqual(j['objects'][0]['in_wishlist'], False)
def test_logged_in_user_info(self):
# login and see if adding a work to the users wishlist causes
# it to show up as in_wishlist in the campaign info
self.client.login(username='test', password='testpass')
r = self.client.get('/api/v1/campaign/', data={
'format': 'json',
'work__editions__isbn_10': '0441012035',
'username': self.user.username,
'api_key': self.user.api_key.key
})
j = json.loads(r.content)
self.assertEqual(j['meta']['logged_in_username'], 'test')
self.assertEqual(j['objects'][0]['in_wishlist'], False)
w = models.Work.objects.get(editions__isbn_10='0441012035')
self.user.wishlist.works.add(w)
r = self.client.get('/api/v1/campaign/', data={
'format': 'json',
'work__editions__isbn_10': '0441012035',
'username': self.user.username,
'api_key': self.user.api_key.key
})
j = json.loads(r.content)
self.assertEqual(j['meta']['logged_in_username'], 'test')
self.assertEqual(j['objects'][0]['in_wishlist'], True)