Skip to content

https and like button #59

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions code/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
-f /usr/share/pip-wheels
Django==1.9.6
Django==1.11.7
Pillow==4.3.0
django-bootstrap-toolkit==2.15.0
django-registration-redux==1.4
Pillow==3.3.0
django-registration-redux==1.9
olefile==0.44
pytz==2017.3
13 changes: 9 additions & 4 deletions code/tango_with_django_project/rango/forms.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from django import forms
from rango.models import Page, Category, UserProfile
from django.forms.widgets import TextInput
from django.core.validators import URLValidator

class CategoryForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Please enter the category name.")
Expand All @@ -13,11 +15,13 @@ class Meta:
model = Category
fields = ('name',)


class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the title of the page.")
url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
url = forms.CharField(max_length=200, help_text="Please enter the URL of the page.", validators=[URLValidator()])
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)

"""
def clean(self):
cleaned_data = self.cleaned_data
url = cleaned_data.get('url')
Expand All @@ -27,7 +31,8 @@ def clean(self):
url = 'http://' + url
cleaned_data['url'] = url

return cleaned_data
return cleaned_data
"""

class Meta:
# Provide an association between the ModelForm and a model
Expand All @@ -45,7 +50,7 @@ class Meta:
class UserProfileForm(forms.ModelForm):
website = forms.URLField(required=False)
picture = forms.ImageField(required=False)

class Meta:
model = UserProfile
exclude = ('user',)
exclude = ('user',)
51 changes: 51 additions & 0 deletions code/tango_with_django_project/rango/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2017-11-26 20:41
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128, unique=True)),
('views', models.IntegerField(default=0)),
('likes', models.IntegerField(default=0)),
('slug', models.SlugField(unique=True)),
],
options={
'verbose_name_plural': 'categories',
},
),
migrations.CreateModel(
name='Page',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=128)),
('url', models.URLField()),
('views', models.IntegerField(default=0)),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rango.Category')),
],
),
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('website', models.URLField(blank=True)),
('picture', models.ImageField(blank=True, upload_to='profile_images')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-27 04:12
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('rango', '0001_initial'),
]

operations = [
migrations.AlterField(
model_name='page',
name='url',
field=models.CharField(max_length=200),
),
]
Empty file.
18 changes: 9 additions & 9 deletions code/tango_with_django_project/rango/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,34 +9,34 @@ class Category(models.Model):
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
slug = models.SlugField(unique=True)

def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)

class Meta:
verbose_name_plural = 'categories'

def __str__(self):
return self.name

class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128)
url = models.URLField()
url = models.CharField(max_length=200)
views = models.IntegerField(default=0)

def __str__(self):
return self.title


class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
# The additional attributes we wish to include.
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)

# Override the __unicode__() method to return out something meaningful!
def __str__(self):
return self.user.username
return self.user.username
70 changes: 36 additions & 34 deletions code/tango_with_django_project/rango/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def visitor_cookie_handler(request):
request.session['last_visit'] = str(datetime.now())
else:
visits = 1
# set the last visit cookie
# set the last visit cookie
request.session['last_visit'] = last_visit_cookie
# update/set the visits cookie
request.session['visits'] = visits
Expand All @@ -47,41 +47,41 @@ def visitor_cookie_handler(request):

def index(request):
#context_dict = {'boldmessage': "Crunchie, creamy, cookie, candy, cupcake!"}

request.session.set_test_cookie()

category_list = Category.objects.order_by('-likes')[:5]

page_list = Page.objects.order_by('-views')[:5]

context_dict = {'categories': category_list, 'pages': page_list}

visitor_cookie_handler(request)

context_dict['visits'] = request.session['visits']

print(request.session['visits'])

response = render(request, 'rango/index.html', context=context_dict)

return response


def about(request):
if request.session.test_cookie_worked():
print("TEST COOKIE WORKED!")
request.session.delete_test_cookie()
# To complete the exercise in chapter 4, we need to remove the following line
# return HttpResponse("Rango says here is the about page. <a href='/rango/'>View index page</a>")

# and replace it with a pointer to ther about.html template using the render method
return render(request, 'rango/about.html',{})

def show_category(request, category_name_slug):
# Create a context dictionary which we can pass
# to the template rendering engine.
context_dict = {}

try:
# Can we find a category name slug with the given name?
# If we can't, the .get() method raises a DoesNotExist exception.
Expand All @@ -90,7 +90,7 @@ def show_category(request, category_name_slug):
# Retrieve all of the associated pages.
# Note that filter() returns a list of page objects or an empty list
pages = Page.objects.filter(category=category)

# Adds our results list to the template context under name pages.
context_dict['pages'] = pages
# We also add the category object from
Expand All @@ -100,7 +100,7 @@ def show_category(request, category_name_slug):

# We get here if we didn't find the specified category.
# Don't do anything -
# the template will display the "no category" message for us.
# the template will display the "no category" message for us.
except Category.DoesNotExist:
context_dict['category'] = None
context_dict['pages'] = None
Expand All @@ -112,8 +112,9 @@ def show_category(request, category_name_slug):

result_list = []
if request.method == 'POST':
query = request.POST['query'].strip()
query = request.POST.get('query')
if query:
query = query.strip()
# Run our Webhose function to get the results list!
result_list = run_query(query)
context_dict['query'] = query
Expand All @@ -122,10 +123,10 @@ def show_category(request, category_name_slug):

# Go render the response and return it to the client.
return render(request, 'rango/category.html', context_dict)




def add_category(request):
form = CategoryForm()
# A HTTP POST?
Expand All @@ -147,8 +148,8 @@ def add_category(request):
# Will handle the bad form (or form details), new form or no form supplied cases.
# Render the form with error messages (if any).
return render(request, 'rango/add_category.html', {'form': form})


def add_page(request, category_name_slug):
try:
category = Category.objects.get(slug=category_name_slug)
Expand All @@ -172,8 +173,8 @@ def add_page(request, category_name_slug):
context_dict = {'form':form, 'category': category}

return render(request, 'rango/add_page.html', context_dict)


def search(request):
result_list = []
if request.method == 'POST':
Expand All @@ -182,8 +183,8 @@ def search(request):
# Run our Webhose function to get the results list!
result_list = run_query(query)
return render(request, 'rango/search.html', {'result_list': result_list})


def register(request):
registered = False
if request.method == 'POST':
Expand All @@ -210,7 +211,7 @@ def register(request):
# else:
# user_form = UserForm()
# profile_form = UserProfileForm()

user_form = UserForm()
profile_form = UserProfileForm()

Expand All @@ -231,6 +232,7 @@ def track_url(request):
page = Page.objects.get(id=page_id)
page.views = page.views + 1
page.save()
print(page.url)
return redirect(page.url)
except:
return HttpResponse("Page id {0} not found".format(page_id))
Expand All @@ -246,13 +248,13 @@ def register_profile(request):
user_profile = form.save(commit=False)
user_profile.user = request.user
user_profile.save()

return redirect('index')
else:
print(form.errors)

context_dict = {'form':form}

return render(request, 'rango/profile_registration.html', context_dict)

class RangoRegistrationView(RegistrationView):
Expand All @@ -265,22 +267,22 @@ def profile(request, username):
user = User.objects.get(username=username)
except User.DoesNotExist:
return redirect('index')

userprofile = UserProfile.objects.get_or_create(user=user)[0]
form = UserProfileForm({'website': userprofile.website, 'picture': userprofile.picture})

if request.method == 'POST':
form = UserProfileForm(request.POST, request.FILES, instance=userprofile)
if form.is_valid():
form.save(commit=True)
return redirect('profile', user.username)
else:
print(form.errors)

return render(request, 'rango/profile.html', {'userprofile': userprofile, 'selecteduser': user, 'form': form})

@login_required
def list_profiles(request):
# user_list = User.objects.all()
userprofile_list = UserProfile.objects.all()
return render(request, 'rango/list_profiles.html', { 'userprofile_list' : userprofile_list})
return render(request, 'rango/list_profiles.html', { 'userprofile_list' : userprofile_list})
Loading