Skip to content

Commit

Permalink
Merge pull request PacktPublishing#11 from kstingel/main
Browse files Browse the repository at this point in the history
ch06 Snippets upload
  • Loading branch information
zenx authored Aug 23, 2022
2 parents 94abda8 + 6b28e86 commit 5179566
Show file tree
Hide file tree
Showing 30 changed files with 1,005 additions and 0 deletions.
62 changes: 62 additions & 0 deletions Snippets/Social-TOC.txt
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,65 @@
03 Summary
06 Sharing Content on Your Website
01 Creating an image bookmarking website
ch06/01/images/admin_00.py
ch06/01/images/models_00.py
ch06/01/images/views_00.py
ch06/01/bookmarks/settings_01.py
01 Building the image model
ch06/01.01/images/models_01.py
ch06/01.01/images/models_02.py
02 Creating many-to-many relationships
ch06/01.02/images/models_01.py
03 Registering the image model in the administration site
Chapter06/bookmarks/images/admin.py
02 Posting content from other websites
ch06/02/images/forms_01.py
01 Cleaning form fields
ch06/02.01/images/forms_01.py
02 Installing the Requests library
Chapter06/bookmarks/images/forms.py
03 Overriding the save() method of a ModelForm
ch06/02.03/images/views_01.py
ch06/02.03/images/urls_01.py
Chapter06/bookmarks/bookmarks/urls.py
Chapter06/bookmarks/images/templates/images/image/create.html
04 Building a bookmarklet with JavaScript
Chapter06/bookmarks/images/templates/images/bookmarklet_launcher.js
Chapter06/bookmarks/account/templates/account/dashboard.html
ch06/02.04/static/js/bookmarklet_01.js
ch06/02.04/static/js/bookmarklet_02.js
ch06/02.04/static/js/bookmarklet_03.js
ch06/02.04/static/js/bookmarklet_04.js
ch06/02.04/static/js/bookmarklet_05.js
Chapter06/bookmarks/static/js/bookmarklet.js
03 Creating a detail view for images
ch06/03/images/views_01.py
ch06/03/images/urls_01.py
Chapter06/bookmarks/images/models.py
ch06/03/images/templates/images/image/detail_01.html
04 Creating image thumbnails using easy-thumbnails
Chapter06/bookmarks/bookmarks/settings.py
ch06/04/images/templates/images/image/detail_01.html
05 Adding asynchronous actions with JavaScript
ch06/05/images/views_01.py
ch06/05/images/urls_01.py
01 Loading JavaScript on DOM ready
ch06/05.01/account/templates/base_01.html
02 Cross-site request forgery for HTTP requests in JavaScript
ch06/05.02/account/templates/base_01.html
03 Performing HTTP requests with JavaScript
ch06/05.03/images/templates/images/image/detail_01.html
ch06/05.03/images/templates/images/image/detail_02.html
ch06/05.03/images/templates/images/image/detail_03.html
Chapter06/bookmarks/images/templates/images/image/detail.html
06 Adding infinite scroll pagination to the image list
Chapter06/bookmarks/images/views.py
Chapter06/bookmarks/images/urls.py
Chapter06/bookmarks/images/templates/images/image/list_images.html
ch06/06/images/templates/images/image/list_01.html
Chapter06/bookmarks/images/templates/images/image/list.html
Chapter06/bookmarks/account/templates/base.html
07 Additional resources
08 Summary
07 Tracking User Actions

2 changes: 2 additions & 0 deletions Snippets/Social_Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ social-auth-app-django = {editable = true, ref = "20fabcd7bd9a8a41910bc5c8ed1bd6
django-extensions = "==3.1.5"
werkzeug = "==2.0.3"
pyopenssl = "==22.0.0"
requests = "==2.28.1"
easy-thumbnails = "==2.8.1"

[dev-packages]
pip = "*"
Expand Down
25 changes: 25 additions & 0 deletions Snippets/ch06/01.01/images/models_01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from django.db import models
from django.conf import settings # new

# new block
class Image(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='images_created',
on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200,
blank=True)
url = models.URLField(max_length=2000)
image = models.ImageField(upload_to='images/%Y/%m/%d/')
description = models.TextField(blank=True)
created = models.DateField(auto_now_add=True)

class Meta:
indexes = [
models.Index(fields=['-created']),
]
ordering = ['-created']

def __str__(self):
return self.title
#
30 changes: 30 additions & 0 deletions Snippets/ch06/01.01/images/models_02.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from django.db import models
from django.conf import settings
from django.utils.text import slugify # new


class Image(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='images_created',
on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200,
blank=True)
url = models.URLField(max_length=2000)
image = models.ImageField(upload_to='images/%Y/%m/%d/')
description = models.TextField(blank=True)
created = models.DateField(auto_now_add=True)

class Meta:
indexes = [
models.Index(fields=['-created']),
]
ordering = ['-created']

def __str__(self):
return self.title

def save(self, *args, **kwargs): # new
if not self.slug: # new
self.slug = slugify(self.title) # new
super().save(*args, **kwargs) # new
33 changes: 33 additions & 0 deletions Snippets/ch06/01.02/images/models_01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from django.db import models
from django.conf import settings
from django.utils.text import slugify


class Image(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='images_created',
on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200,
blank=True)
url = models.URLField(max_length=2000)
image = models.ImageField(upload_to='images/%Y/%m/%d/')
description = models.TextField(blank=True)
created = models.DateField(auto_now_add=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, # new
related_name='images_liked', # new
blank=True) # new

class Meta:
indexes = [
models.Index(fields=['-created']),
]
ordering = ['-created']

def __str__(self):
return self.title

def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super().save(*args, **kwargs)
168 changes: 168 additions & 0 deletions Snippets/ch06/01/bookmarks/settings_01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
"""
Django settings for bookmarks project.
Generated by 'django-admin startproject' using Django 4.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-p+j4&4wmo2yl1s#2y@%lykfay%lfq=7&3r+==ves%7vwsi&l&w'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['mysite.com', 'localhost', '127.0.0.1']


# Application definition

INSTALLED_APPS = [
'account.apps.AccountConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social_django',
'django_extensions',
'images.apps.ImagesConfig', # new
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'bookmarks.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'bookmarks.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

LOGIN_REDIRECT_URL = 'dashboard'
LOGIN_URL = 'login'
LOGOUT_URL = 'logout'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'account.authentication.EmailAuthBackend',
'social_core.backends.facebook.FacebookOAuth2',
'social_core.backends.twitter.TwitterOAuth',
'social_core.backends.google.GoogleOAuth2',
]

SOCIAL_AUTH_FACEBOOK_KEY = '' # Facebook App ID
SOCIAL_AUTH_FACEBOOK_SECRET = '' # Facebook App Secret
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']

SOCIAL_AUTH_TWITTER_KEY = '' # Twitter API Key
SOCIAL_AUTH_TWITTER_SECRET = '' # Twitter API Secret

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '' # Google Client ID
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '' # Google Client Secret

SOCIAL_AUTH_PIPELINE = [
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.auth_allowed',
'social_core.pipeline.social_auth.social_user',
'social_core.pipeline.user.get_username',
'social_core.pipeline.user.create_user',
'account.authentication.create_profile',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
'images.apps.ImagesConfig',
]
3 changes: 3 additions & 0 deletions Snippets/ch06/01/images/admin_00.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
3 changes: 3 additions & 0 deletions Snippets/ch06/01/images/models_00.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
3 changes: 3 additions & 0 deletions Snippets/ch06/01/images/views_00.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.shortcuts import render

# Create your views here.
21 changes: 21 additions & 0 deletions Snippets/ch06/02.01/images/forms_01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from django import forms
from .models import Image


class ImageCreateForm(forms.ModelForm):
class Meta:
model = Image
fields = ['title', 'url', 'description']
widgets = {
'url': forms.HiddenInput,
}
# new block
def clean_url(self):
url = self.cleaned_data['url']
valid_extensions = ['jpg', 'jpeg', 'png']
extension = url.rsplit('.', 1)[1].lower()
if extension not in valid_extensions:
raise forms.ValidationError('The given URL does not ' \
'match valid image extensions.')
return url
#
8 changes: 8 additions & 0 deletions Snippets/ch06/02.03/images/urls_01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.urls import path
from . import views

app_name = 'images'

urlpatterns = [
path('create/', views.image_create, name='create'),
]
Loading

0 comments on commit 5179566

Please sign in to comment.