Skip to content

changed staticfiles to static #12

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 38 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
b9e7dc0
Added new project, tango_with_django_project.
maxwelld90 Jan 11, 2020
38e666f
Added rango app, configured project to include it via INSTALLED_APPS.
maxwelld90 Jan 11, 2020
bac096b
Initial view working, along with rango app URL mappings.
maxwelld90 Jan 11, 2020
ee6fb02
Completed exercises for Chapter 3.
maxwelld90 Jan 11, 2020
077efa6
Added first template (index.html) and necessary configuration for it …
maxwelld90 Jan 11, 2020
e37bac8
We now have working static files, and rango.jpg to test.
maxwelld90 Jan 11, 2020
b3d3552
Included a static file in index.html
maxwelld90 Jan 11, 2020
60bc063
Serving media files now working.
maxwelld90 Jan 11, 2020
9d9511d
Completed exercises for Chapter 4.
maxwelld90 Jan 11, 2020
25c968f
Created models and registered them to the admin interface.
maxwelld90 Jan 11, 2020
c57bc92
Added population script, first version.
maxwelld90 Jan 11, 2020
0235eab
Completed exercises for Chapter 5.
maxwelld90 Jan 11, 2020
986fa05
Added category listing to the index page
maxwelld90 Jan 11, 2020
04a4592
Category slugs taken care of
maxwelld90 Jan 11, 2020
fce330d
Added a new category view, and added link from index page to the said…
maxwelld90 Jan 11, 2020
1a4ae40
Completed exercises for Chapter 6.
maxwelld90 Jan 11, 2020
f2fbd1d
Added basic form functionality, and clean() functionality for the Pag…
maxwelld90 Jan 11, 2020
a8c71c0
Added MAX_LENGTH variables to avoid repetition across classes and forms.
maxwelld90 Jan 11, 2020
b90fc0b
Completed exercises for Chapter 7.
maxwelld90 Jan 11, 2020
37ee7d4
Added base.html template, and converted category.html to use template…
maxwelld90 Jan 11, 2020
dac1d66
Completed exercises for Chapter 8
maxwelld90 Jan 11, 2020
9821984
Added basic teplatetag for displaying categories
maxwelld90 Jan 11, 2020
ee8e647
Completed everything up to the end of Chapter 8. Tests all pass.
maxwelld90 Jan 11, 2020
bf656ac
Added registration functionality
maxwelld90 Jan 11, 2020
2676a9b
Added login functionality.
maxwelld90 Jan 11, 2020
69e410a
Added initial restricted page view.
maxwelld90 Jan 11, 2020
98f9e96
Added logout functionality.
maxwelld90 Jan 11, 2020
04e93b7
base.html links now change depending whether someone is logged in or …
maxwelld90 Jan 11, 2020
0182ccc
Chapter 9 exercises now complete.
maxwelld90 Jan 11, 2020
068e70d
changed staticfiles to static
anilchoudhary Mar 17, 2020
6029546
changed staticfiles to static
anilchoudhary Mar 17, 2020
9c6e7d2
changed staticfiles to static
anilchoudhary Mar 17, 2020
cd7e085
changed staticfiles to static
anilchoudhary Mar 17, 2020
2e3c4bb
changed staticfiles to static
anilchoudhary Mar 17, 2020
0d72ac0
changed staticfiles to static
anilchoudhary Mar 17, 2020
f24f7ca
changed staticfiles to static
anilchoudhary Mar 17, 2020
97af17a
changed staticfiles to static
anilchoudhary Mar 17, 2020
26b9cf0
changed staticfiles to static
anilchoudhary Mar 17, 2020
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
15 changes: 15 additions & 0 deletions tango_with_django_project/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
1 change: 1 addition & 0 deletions tango_with_django_project/media/.keep
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A blank file for ensuring that the media/ directory is included in the media commit.
Binary file added tango_with_django_project/media/cat.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
71 changes: 71 additions & 0 deletions tango_with_django_project/populate_rango.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')

import django
django.setup()
from rango.models import Category, Page

# For an explanation of what is going on here, please refer to the TwD book.

def populate():
python_pages = [
{'title': 'Official Python Tutorial',
'url':'http://docs.python.org/3/tutorial/',
'views': 114,},
{'title':'How to Think like a Computer Scientist',
'url':'http://www.greenteapress.com/thinkpython/',
'views': 53},
{'title':'Learn Python in 10 Minutes',
'url':'http://www.korokithakis.net/tutorials/python/',
'views': 20} ]

django_pages = [
{'title':'Official Django Tutorial',
'url':'https://docs.djangoproject.com/en/2.1/intro/tutorial01/',
'views': 32},
{'title':'Django Rocks',
'url':'http://www.djangorocks.com/',
'views': 12},
{'title':'How to Tango with Django',
'url':'http://www.tangowithdjango.com/',
'views': 1258} ]

other_pages = [
{'title':'Bottle',
'url':'http://bottlepy.org/docs/dev/',
'views': 54},
{'title':'Flask',
'url':'http://flask.pocoo.org',
'views': 64} ]

cats = {'Python': {'pages': python_pages, 'views': 128, 'likes': 64},
'Django': {'pages': django_pages, 'views': 64, 'likes': 32},
'Other Frameworks': {'pages': other_pages, 'views': 32, 'likes': 16} }

for cat, cat_data in cats.items():
c = add_cat(cat, views=cat_data['views'], likes=cat_data['likes'])
for p in cat_data['pages']:
add_page(c, p['title'], p['url'], views=p['views'])

for c in Category.objects.all():
for p in Page.objects.filter(category=c):
print(f'- {c}: {p}')

def add_page(cat, title, url, views=0):
p = Page.objects.get_or_create(category=cat, title=title)[0]
p.url=url
p.views=views
p.save()
return p

def add_cat(name, views=0, likes=0):
c = Category.objects.get_or_create(name=name)[0]
c.views = views
c.likes = likes
c.save()
return c

# Start execution here!
if __name__ == '__main__':
print('Starting Rango population script...')
populate()
Empty file.
13 changes: 13 additions & 0 deletions tango_with_django_project/rango/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from django.contrib import admin
from rango.models import Category, Page
from rango.models import UserProfile

class PageAdmin(admin.ModelAdmin):
list_display = ('title', 'category', 'url')

class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}

admin.site.register(Category, CategoryAdmin)
admin.site.register(Page, PageAdmin)
admin.site.register(UserProfile)
5 changes: 5 additions & 0 deletions tango_with_django_project/rango/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class RangoConfig(AppConfig):
name = 'rango'
46 changes: 46 additions & 0 deletions tango_with_django_project/rango/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from django import forms
from django.contrib.auth.models import User
from rango.models import Page, Category, UserProfile

# We could add these forms to views.py, but it makes sense to split them off into their own file.

class CategoryForm(forms.ModelForm):
name = forms.CharField(max_length=Category.NAME_MAX_LENGTH, help_text="Please enter the category name.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
slug = forms.CharField(widget=forms.HiddenInput(), required=False)

class Meta:
model = Category
fields = ('name',)

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

class Meta:
model = Page
exclude = ('category',)

def clean(self):
cleaned_data = self.cleaned_data
url = cleaned_data.get('url')

if url and not url.startswith('http://'):
url = f'http://{url}'
cleaned_data['url'] = url

return cleaned_data

class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())

class Meta:
model = User
fields = ('username', 'email', 'password',)

class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('website', 'picture',)
41 changes: 41 additions & 0 deletions tango_with_django_project/rango/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from django.db import models
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User

class Category(models.Model):
NAME_MAX_LENGTH = 128

name = models.CharField(max_length=NAME_MAX_LENGTH, unique=True)
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):
TITLE_MAX_LENGTH = 128
URL_MAX_LENGTH = 200

category = models.ForeignKey(Category, on_delete=models.CASCADE)
title = models.CharField(max_length=TITLE_MAX_LENGTH)
url = models.URLField()
views = models.IntegerField(default=0)

def __str__(self):
return self.title

class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)

def __str__(self):
return self.user.username
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django import template
from rango.models import Category

register = template.Library()

@register.inclusion_tag('rango/categories.html')
def get_category_list(current_category=None):
return {'categories': Category.objects.all(),
'current_category': current_category}
3 changes: 3 additions & 0 deletions tango_with_django_project/rango/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
16 changes: 16 additions & 0 deletions tango_with_django_project/rango/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from django.urls import path
from rango import views

app_name = 'rango'

urlpatterns = [
path('', views.index, name='index'),
path('about/', views.about, name='about'),
path('category/<slug:category_name_slug>/', views.show_category, name='show_category'),
path('add_category/', views.add_category, name='add_category'),
path('category/<slug:category_name_slug>/add_page/', views.add_page, name='add_page'),
path('register/', views.register, name='register'),
path('login/', views.user_login, name='login'),
path('restricted/', views.restricted, name='restricted'),
path('logout/', views.user_logout, name='logout'),
]
139 changes: 139 additions & 0 deletions tango_with_django_project/rango/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.urls import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from rango.models import Category, Page
from rango.forms import CategoryForm, PageForm, UserForm, UserProfileForm

def index(request):
category_list = Category.objects.order_by('-likes')[:5]
page_list = Page.objects.order_by('-views')[:5]

context_dict = {}
context_dict['boldmessage'] = 'Crunchy, creamy, cookie, candy, cupcake!'
context_dict['categories'] = category_list
context_dict['pages'] = page_list
context_dict['extra'] = 'From the model solution on GitHub'

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

def about(request):
# Spoiler: you don't need to pass a context dictionary here.
return render(request, 'rango/about.html')

def show_category(request, category_name_slug):
context_dict = {}

try:
category = Category.objects.get(slug=category_name_slug)
pages = Page.objects.filter(category=category)

context_dict['pages'] = pages
context_dict['category'] = category
except Category.DoesNotExist:
context_dict['pages'] = None
context_dict['category'] = None

return render(request, 'rango/category.html', context=context_dict)

@login_required
def add_category(request):
form = CategoryForm()

if request.method == 'POST':
form = CategoryForm(request.POST)

if form.is_valid():
form.save(commit=True)
return redirect(reverse('rango:index'))
else:
print(form.errors)

return render(request, 'rango/add_category.html', {'form': form})

@login_required
def add_page(request, category_name_slug):
try:
category = Category.objects.get(slug=category_name_slug)
except:
category = None

# You cannot add a page to a Category that does not exist... DM
if category is None:
return redirect(reverse('rango:index'))

form = PageForm()

if request.method == 'POST':
form = PageForm(request.POST)

if form.is_valid():
if category:
page = form.save(commit=False)
page.category = category
page.views = 0
page.save()

return redirect(reverse('rango:show_category', kwargs={'category_name_slug': category_name_slug}))
else:
print(form.errors) # This could be better done; for the purposes of TwD, this is fine. DM.

context_dict = {'form': form, 'category': category}
return render(request, 'rango/add_page.html', context=context_dict)

def register(request):
registered = False

if request.method == 'POST':
user_form = UserForm(request.POST)
profile_form = UserProfileForm(request.POST)

if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()

profile = profile_form.save(commit=False)
profile.user = user

if 'picture' in request.FILES:
profile.picture = request.FILES['picture']

profile.save()
registered = True
else:
print(user_form.errors, profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileForm()

return render(request, 'rango/register.html', context={'user_form': user_form, 'profile_form': profile_form, 'registered': registered})

def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')

user = authenticate(username=username, password=password)

if user:
if user.is_active:
login(request, user)
return redirect(reverse('rango:index'))
else:
return HttpResponse("Your Rango account is disabled.")
else:
print(f"Invalid login details: {username}, {password}")
return HttpResponse("Invalid login details supplied.")
else:
return render(request, 'rango/login.html')

@login_required
def restricted(request):
return render(request, 'rango/restricted.html')

@login_required
def user_logout(request):
logout(request)
return redirect(reverse('rango:index'))
Binary file added tango_with_django_project/static/images/rango.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Empty file.
Loading