def index(request): # Request the context of the request. # The context contains information such as the client's machine details, for example. #context = RequestContext(request) # NOT ANYMORE WITH RENDER # Query the database for a list of ALL categories currently stored. # Order the categories by no. likes in descending order. # Retrieve the top 5 only - or all if less than 5. # Place the list in our context_dict dictionary which will be # passed to the template engine. category_list = Category.objects.order_by('-likes')[:5] page_list = Page.objects.order_by('-views')[:5] cat_list = get_category_list() context_dict = {'categories': category_list, 'pages': page_list, 'cat_list': cat_list} # The following two lines are new. # We loop through each category returned, and create a URL # attribute. This attribute stores an encoded URL (e.g. spaces # replaced with underscores). for category in category_list: category.url = Category.encode(category.name) # Return a rendered response to send to the client. # We make use of the shortcut function to make our lives easier. # Note that the first parameter is the template we wish to use. # Get the number of visits to the site. # We use the COOKIES.get() function to obtain the visits cookie. # If the cookie exists, the value returned is casted to an integer. # If the cookie doesn't exist, we default to zero and cast that. visits = int(request.COOKIES.get('visits', '0')) if request.session.get('last_visit'): # The session has a value for The last visit last_visit_time = request.session.get('last_visit') visits = request.session.get('visits', 0) if (datetime.now() - datetime.strptime(last_visit_time[:-7], "%Y-%m-%d %H:%M:%S")).days > 0: request.session['visits'] = visits + 1 request.session['last_visit'] = str(datetime.now()) else: # The get returns None, and the session does not have a value for the last visit. request.session['last_visit'] = str(datetime.now()) request.session['visits'] = 1 # Return response back to the user, updating any cookies that need # changed. response = render(request, 'rango/index.html', context_dict) return response
def get_category_list(max_results=0, starts_with=''): cat_list = [] if starts_with: cat_list = Category.objects.filter(name__istartswith=starts_with) else: cat_list = Category.objects.all() if max_results > 0: if len(cat_list) > max_results: cat_list = cat_list[:max_results] for cat in cat_list: cat.url = Category.encode(cat.name) return cat_list