-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #313 from PdxCodeGuild/Philip-Django-Lab03_Pokedex
This looks great! Nice use of function-based views in this lab. I like the fancy CSS image flip. It doesn't appear that image uploads are working, but that's okay. It looks like `settings.py` is missing the `MEDIA_ROOT` variable to tell the files where to be uploaded. The lab only asked for the image URLs from the JSON data to be saved for each Pokemon using a `CharField`. This doesn't have to be corrected, I just wanted to mention it. Everything looks excellent on this lab. Solid work on the searching and sorting as well. I can't wait to see your capstone!
- Loading branch information
Showing
29 changed files
with
2,814 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
#!/usr/bin/env python | ||
"""Django's command-line utility for administrative tasks.""" | ||
import os | ||
import sys | ||
|
||
|
||
def main(): | ||
"""Run administrative tasks.""" | ||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pokedex.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) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
""" | ||
ASGI config for pokedex project. | ||
It exposes the ASGI callable as a module-level variable named ``application``. | ||
For more information on this file, see | ||
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/ | ||
""" | ||
|
||
import os | ||
|
||
from django.core.asgi import get_asgi_application | ||
|
||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pokedex.settings') | ||
|
||
application = get_asgi_application() |
128 changes: 128 additions & 0 deletions
128
Code/Philip/Django/Lab03_Pokedex/pokedex/pokedex/settings.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,128 @@ | ||
""" | ||
Django settings for pokedex project. | ||
Generated by 'django-admin startproject' using Django 4.0.1. | ||
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 | ||
import os | ||
|
||
# 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-**zsaza72784dpb1iezda*1$o_hmp--k50_36c@!cm7bn1g#0^' | ||
|
||
# SECURITY WARNING: don't run with debug turned on in production! | ||
DEBUG = True | ||
|
||
ALLOWED_HOSTS = [] | ||
|
||
|
||
# Application definition | ||
|
||
INSTALLED_APPS = [ | ||
'django.contrib.admin', | ||
'django.contrib.auth', | ||
'django.contrib.contenttypes', | ||
'django.contrib.sessions', | ||
'django.contrib.messages', | ||
'django.contrib.staticfiles', | ||
'pokedex_app', | ||
] | ||
|
||
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 = 'pokedex.urls' | ||
|
||
TEMPLATES = [ | ||
{ | ||
'BACKEND': 'django.template.backends.django.DjangoTemplates', | ||
'DIRS': [str(BASE_DIR.joinpath('templates'))], | ||
'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 = 'pokedex.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/' | ||
STATICFILES_DIRS = [str(BASE_DIR.joinpath('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' | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
"""pokedex URL Configuration | ||
The `urlpatterns` list routes URLs to views. For more information please see: | ||
https://docs.djangoproject.com/en/4.0/topics/http/urls/ | ||
Examples: | ||
Function views | ||
1. Add an import: from my_app import views | ||
2. Add a URL to urlpatterns: path('', views.home, name='home') | ||
Class-based views | ||
1. Add an import: from other_app.views import Home | ||
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') | ||
Including another URLconf | ||
1. Import the include() function: from django.urls import include, path | ||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) | ||
""" | ||
from django.contrib import admin | ||
from django.urls import path, include | ||
|
||
urlpatterns = [ | ||
path('admin/', admin.site.urls), | ||
path('', include('pokedex_app.urls')), | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
""" | ||
WSGI config for pokedex project. | ||
It exposes the WSGI callable as a module-level variable named ``application``. | ||
For more information on this file, see | ||
https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ | ||
""" | ||
|
||
import os | ||
|
||
from django.core.wsgi import get_wsgi_application | ||
|
||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pokedex.settings') | ||
|
||
application = get_wsgi_application() |
Empty file.
7 changes: 7 additions & 0 deletions
7
Code/Philip/Django/Lab03_Pokedex/pokedex/pokedex_app/admin.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
from django.contrib import admin | ||
from .models import Pokemon, PokemonType | ||
|
||
admin.site.register(Pokemon) | ||
admin.site.register(PokemonType) | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
from django.apps import AppConfig | ||
|
||
|
||
class PokedexAppConfig(AppConfig): | ||
default_auto_field = 'django.db.models.BigAutoField' | ||
name = 'pokedex_app' |
151 changes: 151 additions & 0 deletions
151
Code/Philip/Django/Lab03_Pokedex/pokedex/pokedex_app/management/commands/load_pokemon.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,151 @@ | ||
'''Django Lab03 Pokedex | ||
By Philip Bartoo | ||
January 15, 2022 | ||
Pokedex | ||
Let's build a searchable pokedex! First we'll load the data from a json file into our own database. Then we'll list those pokemon in the page and add search. | ||
The Pokédex (Japanese: ポケモン図鑑 illustrated Pokémon encyclopedia) is a digital encyclopedia for Trainers in the Pokémon world. It gives information about all Pokémon in the world that are contained in its database. | ||
Pokédex entries typically describe a Pokémon in only two or three sentences. They may give background information on the habitat or activities of a Pokémon in the wild or other information on the Pokémon's history or anatomy. | ||
Pokédex entries also include height, weight, cry, footprint, location, other forms, and a picture of the Pokémon. | ||
Pokedex Wiki, Pokemon.com | ||
Part 1 | ||
Create an app pokedex and add two models to store our pokemon, Pokemon and PokemonType. | ||
PokemonType should have the following fields: | ||
name (CharField) | ||
Pokemon should have the following fields: | ||
number (IntegerField) | ||
name (CharField) | ||
height (FloatField) | ||
weight (FloatField) | ||
image_front (CharField) | ||
image_back (CharField) | ||
types (ManyToManyField with PokemonType) | ||
Part 2 | ||
Write a custom management command load_pokemon.py to load the data from pokemon.json into your database. You can do this by saving the file next to your .py file and using opening the file. To handle the types, check out many to many fields. In the first line of your management command, you may want to delete all the records in the table so each time you run it you start with a clean slate. To verify that the data was loaded, open your admin panel and check that the pokemon are there. | ||
Part 3 | ||
Write a view, route and template to show a list of pokemon on the front page. You can either show all the information as a table, or show only their name and icon and link to a detail page with all their information. Use <img src="..."> to display their front and back image. | ||
Part 4 (optional) | ||
Check out the script that creates the json file, you can use it to load even more pokemon into your database! | ||
Notes: This was my first Custom Management Command. | ||
What really helped was looking at the raw JSON and writing down the structure to understand the nesting. | ||
It's like peeling an onion back one layer at a time, where the key that picked the lock was accessing the | ||
first dictionary in the 'data=pokemon['pokemon']' code. The trickiest part is dealing with the types. | ||
First, the types are a list nested within the dictionary for each item. | ||
''' | ||
|
||
from django.core.management.base import BaseCommand, CommandError | ||
from pokedex_app.models import Pokemon,PokemonType | ||
#import requests | ||
import json | ||
#import pyperclip | ||
|
||
class Command(BaseCommand): | ||
help = 'Imports Pokedex JSON' | ||
|
||
def handle(self, *args, **kwargs): | ||
|
||
Pokemon.objects.all().delete() | ||
PokemonType.objects.all().delete() | ||
|
||
file = open("pokemon.json") | ||
pokemon = json.load(file) | ||
data=pokemon['pokemon'] | ||
|
||
for row in data: | ||
number=int(row['number']) | ||
name=row['name'] | ||
height=int(row['height']) | ||
weight=int(row['weight']) | ||
image_front=row['image_front'] | ||
image_back=row['image_back'] | ||
type=row['types'] | ||
|
||
#print(types) | ||
|
||
|
||
|
||
pokemon = Pokemon.objects.create( | ||
number=number, | ||
name=str.title(name), | ||
height=height, | ||
weight=weight, | ||
image_front=image_front, | ||
image_back=image_back | ||
) | ||
for type in type: | ||
type, created = PokemonType.objects.get_or_create(name=type) | ||
pokemon.types.add(type) | ||
#print('success??') | ||
|
||
|
||
#for row in pokemon: | ||
#pokemon = pokemon['pokemon'] | ||
#name = row["Name"] | ||
#pokemon.name = row['Name'] | ||
#pokemon.height = int(row['height']) | ||
#pokemon.weight = int(row['weight']) | ||
#pokemon.image_front = row['image_front'] | ||
#pokemon.image_back = row['image_back'] | ||
#pokemon.type = [type['type']['name'] for type in pokemon['types']] | ||
|
||
#file.close() | ||
|
||
#print(pokemon.type) | ||
''' | ||
print('Creating Pokemon Type Data') | ||
for | ||
url = 'https://pokeapi.co/api/v2/pokemon/3' | ||
response = requests.get(url) | ||
item = response.json() | ||
number = int(item['id']) | ||
name = item['name'] | ||
types = [type['type']['name'] for type in item['types']] | ||
print(name, types) | ||
pokemontype, created = PokemonType.objects.get_or_create(id=number) | ||
print(pokemontype) | ||
data = {'pokemon':[]} | ||
num_pokemon = 1 | ||
for i in range(1, num_pokemon): | ||
# get the data from the pokemon api | ||
response = requests.get('https://pokeapi.co/api/v2/pokemon/' + str(i)) | ||
pokeapi_data = json.loads(response.text) | ||
# extract the relevant portions of data | ||
number = pokeapi_data['id'] | ||
name = pokeapi_data['name'] | ||
height = pokeapi_data['height'] | ||
weight = pokeapi_data['weight'] | ||
image_front = pokeapi_data['sprites']['front_default'] | ||
image_back = pokeapi_data['sprites']['back_default'] | ||
url = 'https://pokemon.fandom.com/wiki/' + name | ||
types = [type['type']['name'] for type in pokeapi_data['types']] | ||
pokemontype, created = PokemonType.objects.get_or_create(name=types) | ||
print(pokemontype) | ||
# put the relevant data into a dictionary | ||
pokemon = { | ||
'number': number, | ||
'name': name, | ||
'height': height, | ||
'weight': weight, | ||
'image_front': image_front, | ||
'image_back': image_back, | ||
'types': types, | ||
'url': url | ||
} | ||
# add the pokemon to our list | ||
data['pokemon'].append(pokemon) | ||
# give the user some feedback | ||
print(str(round(i/num_pokemon*100,2))+'%') | ||
# copy the resulting json to the clipboard | ||
pyperclip.copy(json.dumps(data, indent=4)) | ||
''' |
Oops, something went wrong.