Skip to content

Instantly share code, notes, and snippets.

@spenoir
Created May 23, 2012 11:31
Show Gist options
  • Save spenoir/2774710 to your computer and use it in GitHub Desktop.
Save spenoir/2774710 to your computer and use it in GitHub Desktop.
This is a base CBV that utilises django-activity-stream and Towel to enable user profile following. Towel makes it easy to specify one class that handles all the CRUD operations required for profile viewing and editing.
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from towel.modelview import ModelView
from actstream.models import Follow
from models import MyModel
from forms import UserProfileRegistrationForm, UserRoleSearchForm
class BaseProfileView(ModelView):
"""
This is a base class that utilises django-activity-stream and
django-towel to enable user profile following. Towel makes it
easy to specify one class that handles all the CRUD operations
required for profile viewing and editing.
"""
paginate_by = 20
def adding_allowed(self, request):
return False
def render_detail(self, request, context):
" renders the profile detail view along with following counts "
object = context.get('object')
content_type = ContentType.objects.get_for_model(object).pk
activity_url = reverse('actstream_actor', kwargs={
'content_type_id': content_type, 'object_id': object.pk})
object.followers_count = Follow.objects.filter(object_id=object.id).count()
#object.following_count = Follow.objects.filter(user__id=object.user_id).count()
extra_context = {
'contextual_menu': (
('#overview', 'Overview'),
(activity_url, 'Activity'),
),
}
context.update(extra_context)
return super(BaseProfileView, self).render_detail(request, context)
def render_list(self, request, context):
" renders the search form and a list of results "
# TODO: cache and/or denormalise counts
for object in context.get('object_list'):
object.followers_count = Follow.objects.filter(object_id=object.id).count()
object.following_count = Follow.objects.filter(user__id=object.user_id).count()
return super(BaseProfileView, self).render_list(request, context)
class UserProfileModelView(BaseProfileView):
"""
Example usage of BaseProfileView
"""
search_form = UserProfileSearchForm
def get_form(self, request, instance=None, change=None, **kwargs):
" specify a form for creating/editing the profile "
return UserProfileRegistrationForm
def render_form(self, request, context, change):
" here we are just adding basic context vars specific to edit/create "
extra_context = {
'form_name': 'user_role',
'submit_text': 'Apply to be a User'
}
if request.user.is_authenticated():
if request.user.get_profile():
extra_context['submit_text'] = 'Save'
context.update(extra_context)
return super(UserProfileModelView, self).render_form(request, context, change)
user_role_views = UserProfileModelView(MyModel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment