@login_required<EOL>@ensure_csrf_cookie<EOL>def toggle_favorite(request):
if not request.is_ajax():<EOL><INDENT>return HttpResponseForbidden()<EOL><DEDENT>try:<EOL><INDENT>app, model, pk = request.POST['<STR_LIT>'], request.POST['<STR_LIT>'], int(request.POST['<STR_LIT>'])<EOL><DEDENT>except ValueError:<EOL><INDENT>return HttpResponseBadRequest()<EOL><DEDENT>try:<EOL><INDENT>ctype = ContentType.objects.get(app_label=app, model=model)<EOL>obj = ctype.get_object_for_this_type(id=pk)<EOL><DEDENT>except Favorite.DoesNotExist:<EOL><INDENT>return HttpResponseNotFound()<EOL><DEDENT>try:<EOL><INDENT>fave = Favorite.objects.get(content_type=ctype, object_id=obj.id, user=request.user)<EOL><DEDENT>except Favorite.DoesNotExist:<EOL><INDENT>fave = Favorite(content_object=obj, user=request.user)<EOL>fave.save()<EOL>is_favorite = True<EOL><DEDENT>else:<EOL><INDENT>fave.delete()<EOL>is_favorite = False<EOL><DEDENT>favorites_count = Favorite.objects.filter(content_type=ctype, user=request.user).count()<EOL>return JsonResponse({<EOL>'<STR_LIT>': app,<EOL>'<STR_LIT>': model,<EOL>'<STR_LIT>': pk,<EOL>'<STR_LIT>': is_favorite,<EOL>'<STR_LIT:count>': favorites_count,<EOL>})<EOL>
Add/remove an object to the user's favorites. Checks for existance and adds if not, else removes.
This is the underlying mechanism for adding items to the user 'scrapbook' and favorite scripts.

:param request:
:param file_id:
:return: