def run(self, request, *args, **kwargs): #email = kwargs.get('email', None) email = request.GET.get('email', None) email_is_valid = False if email is not None: try: existant = User.objects.get(email=email) # Return user already registered document = OrderedDict() document['email'] = unicode(email) document['registered'] = True return HttpResponse(content=render_as_json(document), content_type='application/json') # if user does not exist, return valid email except User.DoesNotExist: email_is_valid = True # Return if email is good to go if email_is_valid: document = OrderedDict() document['email'] = unicode(email) document['registered'] = False return HttpResponse(content=render_as_json(document), content_type='application/json') # Return if email is not passed error = OrderedDict() message = unicode(strings.NO_EMAIL) error['message'] = message error_list = [error] return HttpResponseBadRequest(json_error_document(error_list))
def change_location(request): if request.method == 'POST': message = unicode(strings.CHANGE_LOCATION_DOCUMENT_ERROR) try: # Parse data data = json.loads(request.body) section = data.get('section', None) components = data.get('address_components', None) section_ok = validate_section(section) aux_doc = OrderedDict() aux_doc['results'] = [{ 'address_components': components }] json_string = json.dumps(aux_doc) # Grab an address component gmac = GMAC.get_or_create_locality_from_json(json_string) if section_ok and gmac is not None: title = create_title(gmac, section) url = create_url(gmac, section) # Make response document doc = OrderedDict() doc['link'] = OrderedDict() doc['link']['title'] = title doc['link']['href'] = url doc['link']['rel'] = 'section' return HttpResponse( content=render_as_json(doc), content_type='application/json' ) elif not section_ok: message = unicode(strings.SECTION_IS_INVALID) elif gmac is None: message = unicode(strings.GMAC_NOT_FOUND) except JSONDecodeError: pass # At this point the request is somewhat borked doc = OrderedDict() doc['errors'] = [message] return HttpResponseBadRequest( content=render_as_json(doc), content_type='application/json' ) else: message = unicode(strings.CHANGE_LOCATION_ERROR) doc = OrderedDict() doc['errors'] = [message] return HttpResponseBadRequest( content=render_as_json(doc), content_type='application/json' )
def run(self, request, *args, **kwargs): place_id = kwargs.get('place_id', 0) if place_id > 0: user = request.user try: is_done = user.done_place_records.filter( place__pk=place_id ) if is_done.exists(): result = True else: result = False except DonePlace.DoesNotExist: result = False # Build response document = OrderedDict() document['is_done'] = result return HttpResponse( content=render_as_json(document), content_type='application/json' ) # In any other case, return a 404 error = OrderedDict() message = unicode(strings.NON_EXISTANT_PLACE % { 'place_id': place_id, }) error['message'] = message error_list = [error] return HttpResponseNotFound( content=json_error_document(error_list), content_type='application/json' )
def post(self, request, *args, **kwargs): term = request.POST.get('category_type', '') page = request.POST.get('page', 1) next_page = int(page) + 1 start = (RESULTS_PER_PAGE * int(page)) end = (RESULTS_PER_PAGE * next_page) search = (SearchQuerySet().filter(content=term) | SearchQuerySet().filter(placetitle=term) | SearchQuerySet().filter(placedescription=term) | SearchQuerySet().filter(placeaddress=term))[start:end] document = OrderedDict() document['page'] = next_page if not search: document['hide_button'] = True else: raw_html = u'' for element in search: raw_html += render_to_string('circuits/circuit_list_item.html', { 'circuit': element.object, 'user': request.user }) document['count'] = len(search) document["raw_html"] = raw_html return HttpResponse(content=render_as_json(document), content_type='application/json')
def register_event_circuit_favorited( owner, circuit, timestamp=None ): metadata = { 'user': owner.id, 'circuit': circuit.id, } nt = constants.NOTIFICATION_TYPE_CHOICES.CIRCUIT_FAVORITED event = NotifiableEvent( owner=owner, notification_type=nt ) if timestamp is None: timestamp = datetime.datetime.now() metadata['timestamp'] = unicode(timestamp) event.info = render_as_json(metadata) event.save() event.register() return event
def register_event_user_followed( owner, followed, timestamp=None ): metadata = { 'follower' : owner.id, 'followed': followed.id, } nt = constants.NOTIFICATION_TYPE_CHOICES.USER_FOLLOWED event = NotifiableEvent( owner=owner, notification_type=nt, ) if timestamp is None: timestamp = datetime.datetime.now() metadata['timestamp'] = unicode(timestamp) event.info = render_as_json(metadata) event.save() event.register() return event
def register_event_circuit_remixed( owner, remixed_circuit, original_circuit, timestamp=None ): metadata = { 'user' : owner.pk, 'remixed_circuit': remixed_circuit.id, 'original_circuit': original_circuit.id, } nt = constants.NOTIFICATION_TYPE_CHOICES.CIRCUIT_REMIXED event = NotifiableEvent( owner=owner, notification_type=nt, ) if timestamp is None: timestamp = datetime.datetime.now() metadata['timestamp'] = unicode(timestamp) event.info = render_as_json(metadata) event.save() event.register() return event
def post(self,request, *args, **kwargs): term = request.POST.get('category_type','') page = request.POST.get('page',1) next_page = int(page) + 1 start = (RESULTS_PER_PAGE*int(page)) end = (RESULTS_PER_PAGE*next_page) search = ( SearchQuerySet().filter(content=term)| SearchQuerySet().filter(placetitle=term)| SearchQuerySet().filter(placedescription=term)| SearchQuerySet().filter(placeaddress=term) )[start:end] document = OrderedDict() document['page'] = next_page if not search: document['hide_button'] = True else: raw_html = u'' for element in search: raw_html += render_to_string( 'circuits/circuit_list_item.html', {'circuit': element.object, 'user': request.user} ) document['count'] = len(search) document["raw_html"] = raw_html return HttpResponse( content=render_as_json(document), content_type='application/json' )
def register_event_circuit_remixed(owner, remixed_circuit, original_circuit, timestamp=None): metadata = { 'user': owner.pk, 'remixed_circuit': remixed_circuit.id, 'original_circuit': original_circuit.id, } nt = constants.NOTIFICATION_TYPE_CHOICES.CIRCUIT_REMIXED event = NotifiableEvent( owner=owner, notification_type=nt, ) if timestamp is None: timestamp = datetime.datetime.now() metadata['timestamp'] = unicode(timestamp) event.info = render_as_json(metadata) event.save() event.register() return event
def run(self, request, *args, **kwargs): user_id = kwargs.get('user_id', 0) if user_id > 0: try: follower = User.objects.get(pk=user_id) followee_id = request.GET.get('followee_id', 0) if followee_id == 0: followee_id = request.user.pk # Check if the user is different if follower.id != followee_id: try: followee = User.objects.get(pk=followee_id) try: is_following = follower.userprofile.is_following( followee ) except UserProfile.DoesNotExist: is_following = None message = strings.NON_EXISTANT_FOLLOWER_PROFILE except User.DoesNotExist: is_follower = None message = strings.NON_EXISTANT_FOLLOWEE # Send conflict status code if is_following is None: # Follower does not exist error = OrderedDict() error['message'] = unicode(message) errors = [error] content = json_error_document(errors) return HttpResponseConflict( content=content, content_type='application/json', ) else: is_following = False # Build response document = OrderedDict() document['is_following'] = is_following #FIXME: Add a link to the user and to the available ops return HttpResponse( content=render_as_json(document), content_type='application/json', ) except User.DoesNotExist: pass # In any other case, return a 404 error = OrderedDict() message = unicode(strings.NON_EXISTANT_USER) error['message'] = message error_list = [error] return HttpResponseNotFound( content=json_error_document(error_list), content_type='application/json', )
def run(self, request, *args, **kwargs): user_id = kwargs.get('user_id', 0) if user_id > 0: try: follower = User.objects.get(pk=user_id) followee_id = request.GET.get('followee_id', 0) if followee_id == 0: followee_id = request.user.pk # Check if the user is different if follower.id != followee_id: try: followee = User.objects.get(pk=followee_id) try: is_following = follower.userprofile.is_following( followee) except UserProfile.DoesNotExist: is_following = None message = strings.NON_EXISTANT_FOLLOWER_PROFILE except User.DoesNotExist: is_follower = None message = strings.NON_EXISTANT_FOLLOWEE # Send conflict status code if is_following is None: # Follower does not exist error = OrderedDict() error['message'] = unicode(message) errors = [error] content = json_error_document(errors) return HttpResponseConflict( content=content, content_type='application/json', ) else: is_following = False # Build response document = OrderedDict() document['is_following'] = is_following #FIXME: Add a link to the user and to the available ops return HttpResponse( content=render_as_json(document), content_type='application/json', ) except User.DoesNotExist: pass # In any other case, return a 404 error = OrderedDict() message = unicode(strings.NON_EXISTANT_USER) error['message'] = message error_list = [error] return HttpResponseNotFound( content=json_error_document(error_list), content_type='application/json', )
def get_json_representation(self, render_json=True): document = OrderedDict() document['id'] = self.id document['slug'] = self.slug document['description'] = unicode(self.description) document['link'] = self.get_restful_link_metadata('self') if render_json: return render_as_json(document) else: return document
def short_json_representation(place, render_json=True): document = OrderedDict() document['name'] = place.name document['coordinates'] = place.get_coordinates_subdoc() document['address'] = place.address document['link'] = place.get_restful_link_metadata(rel='self') if render_json: return render_as_json(document) else: return document
def get(self, request, *args, **kwargs): document = OrderedDict() # returns the same JSON FS gives document['place_types'] = json.loads( PlaceCategoryCollection.json_representation() ) document['link'] = self.get_restful_link_metadata(rel='self') return HttpResponse( content=render_as_json(document), content_type='application/json' )
def run(self, request, *args, **kwargs): place_id = kwargs.get('place_id', 0) existant_place = Place.objects.filter(pk=place_id) if existant_place.exists(): # get user user = request.user # filter if place is already marked as DonePlace is_done = user.done_place_records.filter( place__pk=place_id ) # check if already favorited if is_done.exists(): message = strings.PLACE_ALREADY_DONE else: # Add DonePlace dp = DonePlace(user=user, place=existant_place[0]) dp.save() # Build response document = OrderedDict() #FIXME: Add a link to the Place document['set_doneplace'] = True # Return response return HttpResponse( content=render_as_json(document), content_type='application/json' ) # Send conflict status code error = OrderedDict() error['message'] = unicode(message) errors = [error] content = json_error_document(errors) return HttpResponseConflict( content=content, content_type='application/json' ) # In any other case, return a 404 error = OrderedDict() message = unicode(strings.NON_EXISTANT_PLACE % { 'place_id': place_id }) error['message'] = message error_list = [error] return HttpResponseNotFound( content=json_error_document(error_list), content_type='application/json' )
def json_representation(placetype, render_json=True): # Document document = OrderedDict() document['name'] = placetype.name document['pluralName'] = placetype.pluralName document['shortName'] = placetype.shortName document['icon_prefix'] = placetype.icon_prefix document['icon_sizes'] = placetype.icon_sizes document['icon_name'] = placetype.icon_name document['link'] = placetype.get_restful_link_metadata(rel='self') if render_json: return render_as_json(document) else: return document
def run(self, request, *args, **kwargs): #email = kwargs.get('email', None) email = request.GET.get('email', None) email_is_valid = False if email is not None: try: existant = User.objects.get(email=email) # Return user already registered document = OrderedDict() document['email'] = unicode(email) document['registered'] = True return HttpResponse( content=render_as_json(document), content_type='application/json' ) # if user does not exist, return valid email except User.DoesNotExist: email_is_valid = True # Return if email is good to go if email_is_valid: document = OrderedDict() document['email'] = unicode(email) document['registered'] = False return HttpResponse( content=render_as_json(document), content_type='application/json' ) # Return if email is not passed error = OrderedDict() message = unicode(strings.NO_EMAIL) error['message'] = message error_list = [error] return HttpResponseBadRequest( json_error_document(error_list) )
def get_json_representation(self, render_json=True): #FIXME: Eventually move to the resource class when implemented document = OrderedDict() document['place_type_id'] = self.place_type_id document['name'] = self.name document['plural_name'] = self.pluralName document['short_name'] = self.shortName # Icons document['icons'] = OrderedDict() document['icons']['default'] = self.get_icon() document['icons']['sizes'] = self.get_icon_dict() if render_json: return render_as_json(document) else: return document
def json_representation(notification, render_json=True): document = OrderedDict() document['id'] = notification.pk document['notification_type'] = notification.notification_type try: document['notified_user'] = \ notification.notified_user.userprofile.get_restful_link_metadata() except UserProfile.DoesNotExist: document['notified_user'] = None document['info'] = notification.make_info_dict() if render_json: return render_as_json(document) else: return document
def run(self, request, *args, **kwargs): place_id = kwargs.get('place_id', 0) existant_place = Place.objects.filter(pk=place_id) if existant_place.exists(): # get user user = request.user # filter if circuit is already favorite is_done = user.done_place_records.filter( place__pk=place_id ) # check if is not marked as Done if not is_done.exists(): message = strings.PLACE_NOT_DONE else: # get DonePlace instance object dp = is_done[0] # delete DonePlace dp.delete() # Build response document = OrderedDict() document['unset_doneplace'] = True return HttpResponse( content=render_as_json(document), content_type='application/json' ) # Send conflict status code error = OrderedDict() error['message'] = unicode(message) errors = [error] content = json_error_document(errors) return HttpResponseConflict( content=content, content_type='application/json' ) # In any other case, return a 404 error = OrderedDict() message = unicode(strings.NON_EXISTANT_PLACE % { 'place_id': place_id }) error['message'] = message error_list = [error] return HttpResponseNotFound( content=json_error_document(error_list), content_type='application/json' )
def run(self, request, *args, **kwargs): user_id = kwargs.get('user_id', 0) if user_id > 0: try: followee = User.objects.get(pk=user_id) follower = request.user if followee == follower: message = strings.SELF_FOLLOW_ERROR elif followee.userprofile.is_follower(follower): message = strings.ALREADY_FOLLOWING_USER else: # Add follower followee.userprofile.add_follower(follower) # Build response document = OrderedDict() document['is_follower'] = True #FIXME: Add a link to the user and to the available ops document['followee_id'] = followee.pk document['follower_id'] = follower.pk return HttpResponse( content=render_as_json(document), content_type='application/json', ) # Send conflict status code error = OrderedDict() error['message'] = unicode(message) errors = [error] content = json_error_document(errors) return HttpResponseConflict( content=content, content_type='application/json', ) except User.DoesNotExist: pass # In any other case, return a 404 error = OrderedDict() message = unicode(strings.NON_EXISTANT_USER) error['message'] = message error_list = [error] return HttpResponseNotFound( content=json_error_document(error_list), content_type='application/json', )
def run(self, request, *args, **kwargs): form = LatLngValidationForm(request.GET) # Bad Request if not form.is_valid(): error_list = error_list_from_form(form, prefix_with_fields=False) return HttpResponseBadRequest( content=json_error_document(error_list), content_type='application/json') # FIXME: Implementation pending # Build response document = OrderedDict() return HttpResponse(content=render_as_json(document), content_type='application/json')
def get_or_create_from_json(json_string, max_items=None, type_list=None): type_list = type_list or [] results = [] try: data = json.loads(json_string) except json.decoder.JSONDecodeError: return None # Create address components records = data['results'] for index, record in enumerate(records): try: components = \ GoogleMapsAddressComponent.get_components_from_json( json_string, index ) objects = GoogleMapsAddressComponent.get_component_objects( components ) # Find wanted objects for obj in objects: if obj is None: continue if obj.component_type in type_list and \ obj not in results: results.append(obj) # Grab geometry / location info if (len(objects)> 0) and ('types' in record) \ and ('political' in record['types']): GoogleMapsAddressComponent.set_location_data( obj=objects[0], record=record ) except MultipleObjectsReturned: log_path = localities_settings.REVERSE_GEOLOCATION_ERROR_LOG json_chunk = render_as_json(records[index]) writelog(log_path, json_chunk) continue # Finally, return collected results return results
def json_representation(place, render_json=True): # Document document = OrderedDict() document['name'] = place.name document['place_type'] = \ place.get_place_type().get_json_representation(False) document['coordinates'] = place.get_coordinates_subdoc() document['address'] = place.address document['city'] = place.get_city_name() document['state'] = place.get_state_name() document['country'] = place.get_country_name() document['phone_number'] = place.phone_number document['website'] = place.website document['link'] = place.get_restful_link_metadata(rel='self') if render_json: return render_as_json(document) else: return document
def register_event_circuit_favorited(owner, circuit, timestamp=None): metadata = { 'user': owner.id, 'circuit': circuit.id, } nt = constants.NOTIFICATION_TYPE_CHOICES.CIRCUIT_FAVORITED event = NotifiableEvent(owner=owner, notification_type=nt) if timestamp is None: timestamp = datetime.datetime.now() metadata['timestamp'] = unicode(timestamp) event.info = render_as_json(metadata) event.save() event.register() return event
def run(self, request, *args, **kwargs): if len(request.body) > 0: # Parse data try: data = json.loads(request.body) except Exception: error = OrderedDict() message = strings.GMAC_JSON_NOT_PARSED error['message'] = unicode(message) error_list = [error] return HttpResponse(content=json_error_document(error_list), content_type='application/json') # Grab an address component gmac = GMAC.get_or_create_locality_from_json(request.body) if gmac is not None: # Build response document = OrderedDict() document['gmac_id'] = gmac.pk return HttpResponse(content=render_as_json(document), content_type='application/json') else: error = OrderedDict() message = strings.GMAC_NOT_FOUND error['message'] = unicode(message) error_list = [error] return HttpResponse(content=json_error_document(error_list), content_type='application/json') else: # Bad Request error = OrderedDict() message = strings.GMAC_LIST_MISSING error['message'] = unicode(message) error_list = [error] return HttpResponseBadRequest( content=json_error_document(error_list), content_type='application/json')
def get_or_create_from_json(json_string, max_items=None, type_list=None): type_list = type_list or [] results = [] try: data = json.loads(json_string) except json.decoder.JSONDecodeError: return None # Create address components records = data['results'] for index, record in enumerate(records): try: components = \ GoogleMapsAddressComponent.get_components_from_json( json_string, index ) objects = GoogleMapsAddressComponent.get_component_objects( components) # Find wanted objects for obj in objects: if obj is None: continue if obj.component_type in type_list and \ obj not in results: results.append(obj) # Grab geometry / location info if (len(objects)> 0) and ('types' in record) \ and ('political' in record['types']): GoogleMapsAddressComponent.set_location_data( obj=objects[0], record=record) except MultipleObjectsReturned: log_path = localities_settings.REVERSE_GEOLOCATION_ERROR_LOG json_chunk = render_as_json(records[index]) writelog(log_path, json_chunk) continue # Finally, return collected results return results
def json_representation(profile, render_json=True): # Gender subdoc gender_subdoc = OrderedDict() gender_subdoc['value'] = profile.gender gender_subdoc['key'] = UserProfile.GENDER_CHOICES.get_key( profile.gender) gender_subdoc['description'] = profile.get_gender_display() # Main document document = OrderedDict() document['id'] = profile.user.pk document['uuid'] = profile.uuid document['name'] = profile.user.get_full_name() document['bio'] = profile.bio document['gender'] = gender_subdoc document['member_since'] = profile.created document['link'] = profile.get_restful_link_metadata(rel='self') if render_json: return render_as_json(document) else: return document
def json_representation(profile, render_json=True): # Gender subdoc gender_subdoc = OrderedDict() gender_subdoc['value'] = profile.gender gender_subdoc['key'] = UserProfile.GENDER_CHOICES.get_key( profile.gender ) gender_subdoc['description'] = profile.get_gender_display() # Main document document = OrderedDict() document['id'] = profile.user.pk document['uuid'] = profile.uuid document['name'] = profile.user.get_full_name() document['bio'] = profile.bio document['gender'] = gender_subdoc document['member_since'] = profile.created document['link'] = profile.get_restful_link_metadata(rel='self') if render_json: return render_as_json(document) else: return document
def get(self, request, *args, **kwargs): """ Returns a collection of notifications with an offset and a limit """ # get user user = request.user form = NotificationCollectionFilterForm(request.GET) if form.is_valid(): document = OrderedDict() document['link'] = self.get_restful_link_metadata(user, rel='self') document['notifications'] = [] # get notifications from Form notifications = form.get_notifications(user) # append each notification metadata to a list for nt in notifications: document['notifications'].append( nt.get_restful_link_metadata()) return HttpResponse(content=render_as_json(document), content_type='application/json')
def register_event_user_followed(owner, followed, timestamp=None): metadata = { 'follower': owner.id, 'followed': followed.id, } nt = constants.NOTIFICATION_TYPE_CHOICES.USER_FOLLOWED event = NotifiableEvent( owner=owner, notification_type=nt, ) if timestamp is None: timestamp = datetime.datetime.now() metadata['timestamp'] = unicode(timestamp) event.info = render_as_json(metadata) event.save() event.register() return event
def circuit_category_listing(request, category_slug, gmac_slug=None): """ Displays the first 10 circuits of a category """ # Find GMAC gmacs = None if gmac_slug is not None: try: gmacs = GMAC.objects.filter(slug=gmac_slug) except GMAC.DoesNotExist: pass cpp = circuit_settings.DEFAULT_CIRCUITS_LIMIT try: category_value = CIRCUIT_CATEGORY_CHOICES.get_value( category_slug.upper()) except KeyError: raise Http404 categories = circuit_category_list() category = CircuitCategory(category_value) params = {} params['category'] = category_value gmac_get_short_formatted_name = None if gmacs is not None: params['pk__in'] = [c.pk for c in Circuit.filter_by_gmacs(gmacs)] gmac_get_short_formatted_name = gmacs[0].get_short_formatted_name() if request.is_ajax(): page = request.POST.get('page', None) if page is not None: page = int(page) else: error_doc = OrderedDict() error_doc['error'] = 'Missing POST parameter: page' return HttpResponse(content=render_as_json(error_doc), content_type='application/json') response = {'page': int(page) + 1} circuits = Circuit.objects.available().filter( **params).order_by('-modified')[page * cpp:(page + 1) * cpp] if circuits: html_response = u'' for circuit in circuits: html_response += render_to_string( 'circuits/circuit_list_item.html', { 'circuit': circuit, 'user': request.user }) response['raw_html'] = html_response else: response['hide_button'] = True return HttpResponse(content=json.dumps(response), content_type='application/json') # FIXME circuits filter should also include location of user circuits = Circuit.objects.available().filter( **params).order_by('-modified')[:cpp] return render( request, 'circuits/categories.html', { 'categories': categories, 'category': category, 'selected_category': category_value, 'category_slug': category_slug, 'is_preferred_category': category.is_followed(request.user), 'circuits': circuits, 'topbar_item': 'explore', 'page_type': 'category', 'gmacs': gmacs, 'gmac_slug': gmac_slug, 'STATIC_MAPS_ROOT': settings.STATIC_MAPS_ROOT, 'GOOGLE_API_KEY': settings.GOOGLE_API_KEY, 'gmac_get_short_formatted_name': gmac_get_short_formatted_name, }, )
def show_home(request, gmac_slug=None): # Find GMAC gmacs = None if gmac_slug is not None: try: gmacs = GMAC.objects.filter(slug=gmac_slug) except GMAC.DoesNotExist: pass params = {} gmac_get_short_formatted_name = None if gmacs is not None: params['pk__in'] = [c.pk for c in Circuit.filter_by_gmacs(gmacs)] gmac_get_short_formatted_name = gmacs[0].get_short_formatted_name() cpp = circuit_settings.DEFAULT_CIRCUITS_LIMIT if request.is_ajax(): page = request.POST.get('page', None) if page is not None: page = int(page) else: error_doc = OrderedDict() error_doc['error'] = unicode(strings.MISSING_PAGE_PARAM_ERROR) return HttpResponse( content=render_as_json(error_doc), content_type='application/json' ) response = { 'page': int(page) + 1 } circuits = Circuit.objects.filter(**params) circuits = circuits.filter(published=True).order_by( '-highlighted', '-modified' )[page * cpp: cpp * (page + 1)] if circuits: html_response = u'' for circuit in circuits: html_response += render_to_string( 'circuits/circuit_list_item.html', {'circuit': circuit, 'user': request.user}) response['raw_html'] = html_response else: response['hide_button'] = True return HttpResponse( json.dumps(response), mimetype='application/json' ) categories = circuit_category_list() # Circuits that are not flagged as 18+ circuits = Circuit.objects.filter(adult_content=False) circuits = circuits.filter(published=True).order_by('?')[:cpp] return render(request, 'circuits/recommendations.html', { 'categories': categories, 'circuits': circuits, 'topbar_item': 'explore', 'page_type': 'recommendation', 'GOOGLE_API_KEY': settings.GOOGLE_API_KEY, 'gmac_slug': gmac_slug, 'gmacs': gmacs, 'gmac_get_short_formatted_name': gmac_get_short_formatted_name, }, )
def circuit_category_listing(request, category_slug, gmac_slug=None): """ Displays the first 10 circuits of a category """ # Find GMAC gmacs = None if gmac_slug is not None: try: gmacs = GMAC.objects.filter(slug=gmac_slug) except GMAC.DoesNotExist: pass cpp = circuit_settings.DEFAULT_CIRCUITS_LIMIT try: category_value = CIRCUIT_CATEGORY_CHOICES.get_value( category_slug.upper() ) except KeyError: raise Http404 categories = circuit_category_list() category = CircuitCategory(category_value) params = {} params['category'] = category_value gmac_get_short_formatted_name = None if gmacs is not None: params['pk__in'] = [ c.pk for c in Circuit.filter_by_gmacs(gmacs)] gmac_get_short_formatted_name = gmacs[0].get_short_formatted_name() if request.is_ajax(): page = request.POST.get('page', None) if page is not None: page = int(page) else: error_doc = OrderedDict() error_doc['error'] = 'Missing POST parameter: page' return HttpResponse( content=render_as_json(error_doc), content_type='application/json' ) response = { 'page': int(page) + 1 } circuits = Circuit.objects.available().filter(**params).order_by( '-modified' )[page * cpp: (page + 1) * cpp] if circuits: html_response = u'' for circuit in circuits: html_response += render_to_string( 'circuits/circuit_list_item.html', {'circuit': circuit, 'user': request.user} ) response['raw_html'] = html_response else: response['hide_button'] = True return HttpResponse( content=json.dumps(response), content_type='application/json' ) # FIXME circuits filter should also include location of user circuits = Circuit.objects.available().filter(**params).order_by( '-modified' )[:cpp] return render(request, 'circuits/categories.html', { 'categories': categories, 'category': category, 'selected_category': category_value, 'category_slug': category_slug, 'is_preferred_category': category.is_followed(request.user), 'circuits': circuits, 'topbar_item': 'explore', 'page_type': 'category', 'gmacs': gmacs, 'gmac_slug': gmac_slug, 'STATIC_MAPS_ROOT': settings.STATIC_MAPS_ROOT, 'GOOGLE_API_KEY': settings.GOOGLE_API_KEY, 'gmac_get_short_formatted_name': gmac_get_short_formatted_name, }, )