id
int64
0
25.6k
text
stringlengths
0
4.59k
400
web browser you should see response like this"resources""core""limit" "remaining" "reset" }"search""limit" "remaining" "reset" }"rate""limit" "remaining" "reset" the information we're interested in is the rate limit for the search api we see at that the limit is requests per minute and that we have requests remaining for the current minute the reset value represents the time in unix or epoch time (the number of seconds since midnight on january when our quota will reset if you reach your quotayou'll get short response that lets you know you've reached the api limit if you reach the limitjust wait until your quota resets note many apis require you to register and obtain an api key in order to make api calls as of this writing github has no such requirementbut if you obtain an api keyyour limits will be much higher visualizing repositories using pygal now that we have some interesting datalet' make visualization showing the relative popularity of python projects on github we'll make an interactive bar chartthe height of each bar will represent the number of stars the project has acquired clicking bar will take you to that project' home on github here' an initial attemptpython_ repos py import requests import pygal from pygal style import lightcolorizedstyle as lcslightenstyle as ls
401
url ' requests get(urlprint("status code:" status_codestore api response in variable response_dict json(print("total repositories:"response_dict['total_count']explore information about the repositories repo_dicts response_dict['items' namesstars [][for repo_dict in repo_dictsv names append(repo_dict['name']stars append(repo_dict['stargazers_count']make visualization my_style ls('# 'base_style=lcsx chart pygal bar(style=my_stylex_label_rotation= show_legend=falsechart title 'most-starred python projects on githubchart x_labels names chart add(''starschart render_to_file('python_repos svg'we start by importing pygal and the pygal styles we'll need for the chart we continue to print the status of the api call response and the total number of repositories foundso we'll know if there was problem with the api call we no longer print information about the specific projects that are returnedbecause that information will be included in the visualization at we create two empty lists to store the data we'll include in the chart we'll need the name of each project in order to label the barsand we'll need the number of stars to determine the height of the bars in the loopwe append the name of each project and number of stars it has to these lists next we define style using the lightenstyle class (alias lsand base it on dark shade of blue we also pass the base_style argument to use the lightcolorizedstyle class (alias lcswe then use bar(to make simple bar chart and pass it my_style we pass two more style argumentswe set the rotation of the labels along the -axis to degrees (x_label_rotation= )and we hide the legendbecause we're plotting only one series on the chart (show_legend=falsewe then give the chart title and set the x_labels attribute to the list names because we don' need this data series to be labeledwe pass an empty string for the label when we add the data at the resulting chart is shown in figure - we can see that the first few projects are significantly more popular than the restbut all of them are important projects in the python ecosystem working with apis
402
refining pygal charts let' refine the styling of our chart we'll be making few different customizationsso first restructure the code slightly by creating configuration object that contains all of our customizations to pass to bar()python_ repos py --snip-make visualization my_style ls('# 'base_style=lcsu my_config pygal config( my_config x_label_rotation my_config show_legend false my_config title_font_size my_config label_font_size my_config major_label_font_size my_config truncate_label my_config show_y_guides false my_config width chart pygal bar(my_configstyle=my_stylechart title 'most-starred python projects on githubchart x_labels names chart add(''starschart render_to_file('python_repos svg'at we make an instance of pygal' config classcalled my_configmodifying the attributes of my_config will customize the appearance of the chart we set the two attributes x_label_rotation and show_legend voriginally passed as keyword arguments when we made an instance of bar at
403
minor labels in this chart are the project names along the -axis and most of the numbers along the -axis the major labels are just the labels on the -axis that mark off increments of stars these labels will be largerwhich is why we differentiate between the two at we use truncate_label to shorten the longer project names to characters (when you hover over truncated project name on your screenthe full name will pop up nextwe hide the horizontal lines on the graph by setting show_y_guides to false finallyat we set custom width so the chart will use more of the available space in the browser now when we make an instance of bar at {we pass my_config as the first argumentand it sends all of our configuration settings in one argument we can make as many style and configuration changes as we want through my_configand the line at won' change figure - shows the restyled chart figure - the styling for the chart has been refined adding custom tooltips in pygalhovering the cursor over an individual bar shows the information that the bar represents this is commonly called tooltipand in this case it currently shows the number of stars project has let' create custom tooltip to show each project' description as well let' look at short example using the first three projects plotted individually with custom labels passed for each bar to do thiswe'll pass list of dictionaries to add(instead of list of valuesbar_ descriptions py import pygal from pygal style import lightcolorizedstyle as lcslightenstyle as ls my_style ls('# 'base_style=lcschart pygal bar(style=my_stylex_label_rotation= show_legend=falseworking with apis
404
chart x_labels ['httpie''django''flask' plot_dicts {'value' 'label''description of httpie '}{'value' 'label''description of django '}{'value' 'label''description of flask '} chart add(''plot_dictschart render_to_file('bar_descriptions svg'at we define list called plot_dicts that contains three dictionariesone for the httpie projectone for the django projectand one for flask each dictionary has two keys'valueand 'labelpygal uses the number associated with 'valueto figure out how tall each bar should beand it uses the string associated with 'labelto create the tooltip for each bar for examplethe first dictionary at will create bar representing project with , starsand its tooltip will say description of httpie the add(method needs string and list when we call add()we pass in the list of dictionaries representing the bars (plot_dictsw figure - shows one of the tooltips pygal includes the number of stars as default tooltip in addition to the custom tooltip we passed it figure - each bar has customized tooltip label plotting the data to plot our datawe'll generate plot_dicts automatically for the projects returned by the api call
405
python_ repos py --snip-explore information about the repositories repo_dicts response_dict['items'print("number of items:"len(repo_dicts) namesplot_dicts [][for repo_dict in repo_dictsnames append(repo_dict['name'] plot_dict 'value'repo_dict['stargazers_count']'label'repo_dict['description']plot_dicts append(plot_dictmake visualization my_style ls('# 'base_style=lcs--snip- chart add(''plot_dictschart render_to_file('python_repos svg'at we make an empty list for names and an empty list for plot_dicts we still need the names list in order to generate the labels for the -axis inside the loop we create the dictionary plot_dict for each project we store the number of stars with the key 'valueand the project description with the key 'labelin each plot_dict we then append each project' plot_dict to plot_dicts at we pass the list plot_dicts to add(figure - shows the resulting chart figure - hovering over bar shows the project' description working with apis
406
pygal also allows you to use each bar in the chart as link to website to add this capabilitywe just add one line to our codeleveraging the dictionary we've set up for each project we add new key-value pair to each project' plot_dict using the key 'xlink'python_ repos py --snip-namesplot_dicts [][for repo_dict in repo_dictsnames append(repo_dict['name']plot_dict 'value'repo_dict['stargazers_count']'label'repo_dict['description']'xlink'repo_dict['html_url']plot_dicts append(plot_dict--snip-pygal uses the url associated with 'xlinkto turn each bar into an active link you can click any of the bars in the chartand the github page for that project will automatically open in new tab in your browser now you have an interactiveinformative visualization of data retrieved through an apithe hacker news api to explore how you would use api calls on other siteswe'll look at hacker news (about programming and technologyand engage in lively discussions about those articles hacker newsapi provides access to data about all submissions and comments on the sitewhich is available without having to register for key the following call returns information about the current top article as of this writingthe response is dictionary of information about the article with the id 'url'''type''story''title''new horizonsnasa spacecraft speeds past pluto''descendants' 'score' 'time' 'text'''
407
'id' 'kids'[ the dictionary contains number of keys we can work withsuch as 'urlu and 'titlev the key 'descendantscontains the number of comments an article has received the key 'kidsprovides the ids of all comments made directly in response to this submission each of these comments may have kids of their own as wellso the number of descendants submission has can be greater than its number of kids let' make an api call that returns the ids of the current top articles on hacker newsand then examine each of the top articleshn_ submissions py import requests from operator import itemgetter make an api call and store the response url ' requests get(urlprint("status code:" status_codeprocess information about each submission submission_ids json( submission_dicts [for submission_id in submission_ids[: ]make separate api call for each submission url ('str(submission_idjson'submission_r requests get(urlprint(submission_r status_coderesponse_dict submission_r json( submission_dict 'title'response_dict['title']'link'''comments'response_dict get('descendants' submission_dicts append(submission_dictsubmission_dicts sorted(submission_dictskey=itemgetter('comments')reverse=truefor submission_dict in submission_dictsprint("\ntitle:"submission_dict['title']print("discussion link:"submission_dict['link']print("comments:"submission_dict['comments']firstwe make the api call and print the status of the response this api call returns list containing the ids of the most popular articles on hacker news at the time the call is issued we then convert the response working with apis
408
ids to build set of dictionaries that each store information about one of the current submissions we set up an empty list called submission_dicts at to store these dictionaries we then loop through the ids of the top submissions we make new api call for each submission by generating url that includes the current value of submission_id we print the status of each request so we can see whether it is successful at we create dictionary for the submission currently being processedwhere we store the title of the submission and link to the discussion page for that item at we store the number of comments in the dictionary if an article has no comments yetthe key 'descendantswill not be present when you're not sure if key exists in dictionaryuse the dict get(methodwhich returns the value associated with the given key if it exists or the value you provide if the key doesn' exist ( in this examplefinallywe append each submission_dict to the list submission_dicts submissions on hacker news are ranked according to an overall scorebased on number of factors including how many times it' been voted uphow many comments it' receivedand how recent the submission is we want to sort the list of dictionaries by the number of comments to do thiswe use function called itemgetter({which comes from the operator module we pass this function the key 'comments'and it pulls the value associated with that key from each dictionary in the list the sorted(function then uses this value as its basis for sorting the list we sort the list in reverse order to place the most-commented stories first once the list is sortedwe loop through the list at and print out three pieces of information about each of the top submissionsthe titlea link to the discussion pageand the number of comments the submission currently hasstatus code --snip-titlefirefox deactivates flash by default discussion linkcomments titlenew horizonsnasa spacecraft speeds past pluto discussion linkcomments titleiran nuclear deal is reached with world powers discussion linkcomments
409
discussion linkcomments titleour nexus devices are about to explode discussion linkcomments --snip-you would use similar process to access and analyze information with any api with this datayou could make visualization showing which submissions have inspired the most active recent discussions try it yourse lf - other languagesmodify the api call in python_repos py so it generates chart showing the most popular projects in other languages try languages such as javascriptrubycjavaperlhaskelland go - active discussionsusing the data from hn_submissions pymake bar chart showing the most active discussions currently happening on hacker news the height of each bar should correspond to the number of comments each submission has the label for each bar should include the submission' titleand each bar should act as link to the discussion page for that submission - testing python_repos pyin python_repos pywe printed the value of status_code to make sure the api call was successful write program called test_python_repos pywhich uses unittest to assert that the value of status_code is figure out some other assertions you can make--for examplethat the number of items returned is expected and that the total number of repositories is greater than certain amount summary in this you learned how to use apis to write self-contained programs that automatically gather the data they need and use that data to create visualization we used the github api to explore the most-starred python projects on githuband we looked briefly at the hacker news api as well you learned how to use the requests package to automatically issue an api call to github and how to process the results of that call we also introduced some pygal settings that further customize the appearance of the charts you generate in the final project we'll use django to build web application working with apis
410
app ic
411
ge ting ta te ith dja ngo behind the scenestoday' websites are actually rich applications that act like fully developed desktop applications python has great set of tools for building web applications in this you'll learn how to use django (learning log--an online journal system that lets you keep track of information you've learned about particular topics we'll write specification for this projectand then we'll define models for the data the app will work with we'll use django' admin system to enter some initial data and then learn to write views and templates so django can build the pages of our site django is web framework-- set of tools designed to help you build interactive websites django can respond to page requests and make it
412
and we'll refine the learning log project and then deploy it to live server so you (and your friendscan use it setting up project when beginning projectyou first need to describe the project in specificationor spec then you'll set up virtual environment to build the project in writing spec full spec details the project goalsdescribes the project' functionalityand discusses its appearance and user interface like any good project or business plana spec should keep you focused and help keep your project on track we won' write full project spec herebut we'll lay out few clear goals to keep our development process focused here' the spec we'll usewe'll write web app called learning log that allows users to log the topics they're interested in and to make journal entries as they learn about each topic the learning log home page should describe the site and invite users to either register or log in once logged ina user should be able to create new topicsadd new entriesand read and edit existing entries when you learn about new topickeeping journal of what you've learned can be helpful in tracking and revisiting information good app makes this process efficient creating virtual environment to work with djangowe'll first set up virtual environment to work in virtual environment is place on your system where you can install packages and isolate them from all other python packages separating one project' libraries from other projects is beneficial and will be necessary when we deploy learning log to server in create new directory for your project called learning_logswitch to that directory in terminaland create virtual environment if you're using python you should be able to create virtual environment with the following commandlearning_logpython - venv ll_env learning_loghere we're running the venv module and using it to create virtual environment named ll_env if this worksmove on to "activating the virtual environmenton page if it doesn' workread the next section"installing virtualenv
413
if you're using an earlier version of python or if your system isn' set up to use the venv module correctlyyou can install the virtualenv package to install virtualenventer the followingpip install --user virtualenv keep in mind that you might need to use slightly different version of this command (if you haven' used pip yetsee "installing python packages with pipon page note if you're using linux and this still doesn' workyou can install virtualenv through your system' package manager on ubuntufor examplethe command sudo apt-get install python-virtualenv will install virtualenv change to the learning_log directory in terminaland create virtual environment like thislearning_logvirtualenv ll_env new python executable in ll_env/bin/python installing setuptoolspip done learning_lognote if you have more than one version of python installed on your systemyou should specify the version for virtualenv to use for examplethe command virtualenv ll_env --python=python will create virtual environment that uses python activating the virtual environment now that we have virtual environment set upwe need to activate it with the following commandlearning_logsource ll_env/bin/activate (ll_env)learning_logthis command runs the script activate in ll_env/bin when the environment is activeyou'll see the name of the environment in parenthesesas shown at uthen you can install packages to the environment and use packages that have already been installed packages you install in ll_env will be available only while the environment is active note if you're using windowsuse the command ll_env\scripts\activate (without the word sourceto activate the virtual environment to stop using virtual environmententer deactivate(ll_env)learning_logdeactivate learning_loggetting started with django
414
running in installing django once you've created your virtual environment and activated itinstall django(ll_env)learning_logpip install django installing collected packagesdjango successfully installed django cleaning up (ll_env)learning_logbecause we're working in virtual environmentthis command is the same on all systems there' no need to use the --user flagand there' no need to use longer commands like python - pip install package_name keep in mind that django will be available only when the environment is active creating project in django without leaving the active virtual environment (remember to look for ll_env in parentheses)enter the following commands to create new projectu (ll_env)learning_logdjango-admin py startproject learning_log (ll_env)learning_logls learning_log ll_env manage py (ll_env)learning_logls learning_log __init__ py settings py urls py wsgi py the command at tells django to set up new project called learning_log the dot at the end of the command creates the new project with directory structure that will make it easy to deploy the app to server when we're finished developing it note don' forget this dotor you may run into some configuration issues when we deploy the app if you forget the dotdelete the files and folders that were created (except ll_env)and run the command again running the ls command (dir on windowsv shows that django has created new directory called learning_log it also created file called manage pywhich is short program that takes in commands and feeds them to the relevant part of django to run them we'll use these commands to manage tasks like working with databases and running servers the learning_log directory contains four files wthe most important of which are settings pyurls pyand wsgi py the settings py file controls how django interacts with your system and manages your project we'll modify few of these settings and add some settings of our own as the project
415
browser requests the wsgi py file helps django serve the files it creates the filename is an acronym for web server gateway interface creating the database because django stores most of the information related to project in databasewe need to create database that django can work with to create the database for the learning log projectenter the following command (still in an active environment)(ll_env)learning_logpython manage py migrate operations to performsynchronize unmigrated appsmessagesstaticfiles apply all migrationscontenttypessessionsauthadmin --snip-applying sessions _initial ok (ll_env)learning_logls db sqlite learning_log ll_env manage py any time we modify databasewe say we're migrating the database issuing the migrate command for the first time tells django to make sure the database matches the current state of the project the first time we run this command in new project using sqlite (more about sqlite in moment)django will create new database for us at django reports that it will make the database tables needed to store the information we'll use in this project (synchronize unmigrated apps)and then make sure the database structure matches the current code (apply all migrationsrunning the ls command shows that django created another file called db sqlite sqlite is database that runs off single fileit' ideal for writing simple apps because you won' have to pay much attention to managing the database viewing the project let' make sure that django has set up the project properly enter the runserver command as follows(ll_env)learning_logpython manage py runserver performing system checks system check identified no issues ( silencedjuly : : django version using settings 'learning_log settingsw starting development server at quit the server with control- django starts server so you can view the project on your system to see how well it works when you request page by entering url in browserthe django server responds to that request by building the appropriate page and sending that page to the browser getting started with django
416
it reports the version of django in use and the name of the settings file being usedand at it reports the url where the project is being served the url requests on port on your computer--called localhost the term localhost refers to server that only processes requests on your systemit doesn' allow anyone else to see the pages you're developing now open web browser and enter the url like figure - page that django creates to let you know all is working properly so far keep the server running for nowbut when you want to stop the server you can do so by pressing ctrl- figure - everything is working so far note if you receive the error message that port is already in usetell django to use different port by entering python manage py runserver and cycle through higher numbers until you find an open port try it yourse lf - new projectsto get better idea of what django doesbuild couple of empty projects and look at what it creates make new folder with simple namelike instabook or facegram (outside of your learning_log directory)navigate to that folder in terminaland create virtual environment install djangoand run the command django-admin py startproject instabook (make sure you include the dot at the end of the commandlook at the files and folders this command createsand compare them to learning log do this few times until you're familiar with what django creates when starting new project then delete the project directories if you wish
417
django project is organized as group of individual apps that work together to make the project work as whole for nowwe'll create just one app to do most of the work for our project we'll add another app to manage user accounts in you should still be running runserver in the terminal window you opened earlier open new terminal window (or taband navigate to the directory that contains manage py activate the virtual environmentand then run the startapp commandlearning_logsource ll_env/bin/activate (ll_env)learning_logpython manage py startapp learning_logs (ll_env)learning_logls db sqlite learning_log learning_logs ll_env manage py (ll_env)learning_logls learning_logsadmin py __init__ py migrations models py tests py views py the command startapp appname tells django to create the infrastructure needed to build an app if you look in the project directory nowyou'll see new folder called learning_logs open that folder to see what django has created the most important files are models pyadmin pyand views py we'll use models py to define the data we want to manage in our app we'll get to admin py and views py little later defining models let' think about our data for moment each user will need to create number of topics in their learning log each entry they make will be tied to topicand these entries will be displayed as text we'll also need to store the timestamp of each entry so we can show users when they made each entry open the file models pyand look at its existing contentmodels py from django db import models create your models here module called models is being imported for usand we're being invited to create models of our own model tells django how to work with the data that will be stored in the app code-wisea model is just classit has attributes and methodsjust like every class we've discussed here' the model for the topics users will storefrom django db import models class topic(models model)""" topic the user is learning about"" text models charfield(max_length= date_added models datetimefield(auto_now_add=truegetting started with django
418
def __str__(self)"""return string representation of the model ""return self text we've created class called topicwhich inherits from model-- parent class included in django that defines the basic functionality of model only two attributes are in the topic classtext and date_added the text attribute is charfield-- piece of data that' made up of charactersor text you use charfield when you want to store small amount of textsuch as namea titleor city when we define charfield attributewe have to tell django how much space it should reserve in the database here we give it max_length of characterswhich should be enough to hold most topic names the date_added attribute is datetimefield-- piece of data that will record date and time we pass the argument auto_add_now=truewhich tells django to automatically set this attribute to the current date and time whenever the user creates new topic note to see the different kinds of fields you can use in modelsee the django model field reference at fieldsyou won' need all the information right nowbut it will be extremely useful when you're developing your own apps we need to tell django which attribute to use by default when it displays information about topic django calls __str__(method to display simple representation of model here we've written __str__(method that returns the string stored in the text attribute note if you're using python you should call the __str__(method __unicode__(instead the body of the method is identical activating models to use our modelswe have to tell django to include our app in the overall project open settings py (in the learning_log/learning_log directory)and you'll see section that tells django which apps are installed in the projectsettings py --snip-installed_apps 'django contrib admin''django contrib auth''django contrib contenttypes''django contrib sessions''django contrib messages''django contrib staticfiles'--snip-
419
the project add our app to this tuple by modifying installed_apps so it looks like this--snip-installed_apps --snip-'django contrib staticfiles'my apps 'learning_logs'--snip-grouping apps together in project helps to keep track of them as the project grows to include more apps here we start section caled my appswhich includes only learning_logs for now nextwe need to tell django to modify the database so it can store information related to the model topic from the terminalrun the following command(ll_env)learning_logpython manage py makemigrations learning_logs migrations for 'learning_logs' _initial pycreate model topic (ll_env)learning_logthe command makemigrations tells django to figure out how to modify the database so it can store the data associated with any new models we've defined the output here shows that django has created migration file called _initial py this migration will create table for the model topic in the database now we'll apply this migration and have django modify the database for us(ll_env)learning_logpython manage py migrate --snip-running migrationsrendering model states done applying learning_logs _initial ok most of the output from this command is identical to the output from the first time we issued the migrate command the line we need to check appears at uwhere django confirms that everything worked ok when it applied the migration for learning_logs whenever we want to modify the data that learning log manageswe'll follow these three stepsmodify models pycall makemigrations on learning_logsand tell django to migrate the project getting started with django
420
when you define models for an appdjango makes it easy for you to work with your models through the admin site site' administrators use the admin sitenot site' general users in this sectionwe'll set up the admin site and use it to add some topics through the topic model setting up superuser django allows you to create user who has all privileges available on the sitecalled superuser privilege controls the actions user can take the most restrictive privilege settings allow user to only read public information on the site registered users typically have the privilege of reading their own private data and some selected information available only to members to effectively administer web applicationthe site owner usually needs access to all information stored on the site good administrator is careful with their userssensitive informationbecause users put lot of trust into the apps they access to create superuser in djangoenter the following command and respond to the prompts(ll_env)learning_logpython manage py createsuperuser username (leave blank to use 'ehmatthes')ll_admin email addressw passwordpassword (again)superuser created successfully (ll_env)learning_logwhen you issue the command createsuperuserdjango prompts you to enter username for the superuser here we're using ll_adminbut you can enter any username you want you can enter an email address if you want or just leave this field blank you'll need to enter your password twice note some sensitive information can be hidden from site' administrators for exampledjango doesn' actually store the password you enterinsteadit stores string derived from the passwordcalled hash each time you enter your passworddjango hashes your entry and compares it to the stored hash if the two hashes matchyou're authenticated by requiring hashes to matchif an attacker gains access to site' databasethey'll be able to read its stored hashes but not the passwords when site is set up properlyit' almost impossible to get the original passwords from the hashes registering model with the admin site django includes some models in the admin site automaticallysuch as user and groupbut the models we create need to be registered manually
421
admin py in the same directory as models pyadmin py from django contrib import admin register your models here to register topic with the admin siteenterfrom django contrib import admin from learning_logs models import topic admin site register(topicthis code imports the model we want to registertopic uand then uses admin site register( to tell django to manage our model through the admin site now use the superuser account to access the admin site go to localhost: /admin/enter the username and password for the superuser you just createdand you should see screen like the one in figure - this page allows you to add new users and groups and change existing ones we can also work with data related to the topic model that we just defined figure - the admin site with topic included note if you see message in your browser that the web page is not availablemake sure you still have the django server running in terminal window if you don'tactivate virtual environment and reissue the command python manage py runserver adding topics now that topic has been registered with the admin sitelet' add our first topic click topics to go to the topics pagewhich is mostly emptybecause we have no topics to manage yet click addand you'll see form for adding getting started with django
422
the topics admin pageand you'll see the topic you just created let' create second topic so we'll have more data to work with click add againand create second topicrock climbing when you click saveyou'll be sent back to the main topics page againand you'll see both chess and rock climbing listed defining the entry model to record what we've been learning about chess and rock climbingwe need to define model for the kinds of entries users can make in their learning logs each entry needs to be associated with particular topic this relationship is called many-to-one relationshipmeaning many entries can be associated with one topic here' the code for the entry modelmodels py from django db import models class topic(models model)--snip- class entry(models model)"""something specific learned about topic"" topic models foreignkey(topicw text models textfield(date_added models datetimefield(auto_now_add=truex class metaverbose_name_plural 'entriesdef __str__(self)"""return string representation of the model ""return self text[: the entry class inherits from django' base model classjust as topic did the first attributetopicis foreignkey instance foreign key is database termit' reference to another record in the database this is the code that connects each entry to specific topic each topic is assigned keyor idwhen it' created when django needs to establish connection between two pieces of datait uses the key associated with each piece of information we'll use these connections shortly to retrieve all the entries associated with certain topic next is an attribute called textwhich is an instance of textfield this kind of field doesn' need size limitbecause we don' want to limit the size of individual entries the date_added attribute allows us to present entries in the order they were created and to place timestamp next to each entry at we nest the meta class inside our entry class meta holds extra information for managing modelhere it allows us to set special attribute telling django to use entries when it needs to refer to more than one entry
423
the __str__(method tells django which information to show when it refers to individual entries because an entry can be long body of textwe tell django to show just the first characters of text we also add an ellipsis to clarify that we're not always displaying the entire entry migrating the entry model because we've added new modelwe need to migrate the database again this process will become quite familiaryou modify models pyrun the command python manage py makemigrations app_nameand then run the command python manage py migrate migrate the database and check the output(ll_env)learning_logpython manage py makemigrations learning_logs migrations for 'learning_logs' _entry pycreate model entry (ll_env)learning_logpython manage py migrate operations to perform--snip- applying learning_logs _entry ok new migration called _entry py is generatedwhich tells django how to modify the database to store information related to the model entry when we issue the migrate commandwe see that django applied this migrationand everything was okay registering entry with the admin site we also need to register the entry model here' what admin py should look like nowadmin py from django contrib import admin from learning_logs models import topicentry admin site register(topicadmin site register(entrygo back to under learning_logs click the add link for entriesor click entriesand then choose add entry you should see drop-down list to select the topic you're creating an entry for and text box for adding an entry select chess from the drop-down listand add an entry here' the first entry madethe opening is the first part of the gameroughly the first ten moves or so in the openingit' good idea to do three things-bring out your bishops and knightstry to control the center of the boardand castle your king getting started with django
424
when to follow these guidelines and when to disregard these suggestions when you click saveyou'll be brought back to the main admin page for entries here you'll see the benefit of using text[: as the string representation for each entryit' much easier to work with multiple entries in the admin interface if you see only the first part of an entry rather than the entire text of each entry make second entry for chess and one entry for rock climbing so we have some initial data here' second entry for chessin the opening phase of the gameit' important to bring out your bishops and knights these pieces are powerful and maneuverable enough to play significant role in the beginning moves of game and here' first entry for rock climbingone of the most important concepts in climbing is to keep your weight on your feet as much as possible there' myth that climbers can hang all day on their arms in realitygood climbers have practiced specific ways of keeping their weight over their feet whenever possible these three entries will give us something to work with as we continue to develop learning log the django shell now that we've entered some datawe can examine that data programmatically through an interactive terminal session this interactive environment is called the django shelland it' great environment for testing and trouble shooting your project here' an example of an interactive shell session(ll_env)learning_logpython manage py shell from learning_logs models import topic topic objects all([the command python manage py shell (run in an active virtual environmentlaunches python interpreter that you can use to explore the data stored in your project' database here we import the model topic from the learning_logs models module we then use the method topic objects all(to get all of the instances of the model topicthe list that' returned is called queryset we can loop over queryset just as we' loop over list here' how you can see the id that' been assigned to each topic objecttopics topic objects all(for topic in topics
425
print(topic idtopic chess rock climbing we store the queryset in topicsand then print each topic' id attribute and the string representation of each topic we can see that chess has an id of and rock climbing has an id of if you know the id of particular objectyou can get that object and examine any attribute the object has let' look at the text and date_added values for chesst topic objects get(id= text 'chesst date_added datetime datetime( tzinfo=we can also look at the entries related to certain topic earlier we defined the topic attribute for the entry model this was foreignkeya connection between each entry and topic django can use this connection to get every entry related to certain topiclike thisu entry_set all([<entryin the opening phase of the gameit' important >to get data through foreign key relationshipyou use the lowercase name of the related model followed by an underscore and the word set for examplesay you have the models pizza and toppingand topping is related to pizza through foreign key if your object is called my_pizzarepresenting single pizzayou can get all of the pizza' toppings using the code my_pizza topping_set all(we'll use this kind of syntax when we begin to code the pages users can request the shell is very useful for making sure your code retrieves the data you want it to if your code works as you expect it to in the shellyou can expect it to work properly in the files you write within your project if your code generates errors or doesn' retrieve the data you expect it toit' much easier to troubleshoot your code in the simple shell environment than it is within the files that generate web pages we won' refer to the shell muchbut you should continue using it to practice working with django' syntax for accessing the data stored in the project note each time you modify your modelsyou'll need to restart the shell to see the effects of those changes to exit shell sessionenter ctrl-don windows enter ctrl- and then press enter getting started with django
426
- short entriesthe __str__(method in the entry model currently appends an ellipsis to every instance of entry when django shows it in the admin site or the shell add an if statement to the __str__(method that adds an ellipsis only if the entry is more than characters long use the admin site to add an entry that' fewer than characters in lengthand check that it doesn' have an ellipsis when viewed - the django apiwhen you write code to access the data in your projectyou're writing query skim through the documentation for querying your data at you see will look new to youbut it will be quite useful as you start to work on your own projects - pizzeriastart new project called pizzeria with an app called pizzas define model pizza with field called namewhich will hold name values such as hawaiian and meat lovers define model called topping with fields called pizza and name the pizza field should be foreign key to pizzaand name should be able to hold values such as pineapplecanadian baconand sausage register both models with the admin siteand use the site to enter some pizza names and toppings use the shell to explore the data you entered making pagesthe learning log home page usuallymaking web pages with django consists of three stagesdefining urlswriting viewsand writing templates firstyou must define patterns for urls url pattern describes the way the url is laid out and tells django what to look for when matching browser request with site url so it knows which page to return each url then maps to particular view--the view function retrieves and processes the data needed for that page the view function often calls templatewhich builds page that browser can read to see how this workslet' make the home page for learning log we'll define the url for the home pagewrite its view functionand create simple template because all we're doing is making sure learning log works as it' supposed towe'll keep the page simple for now functioning web app is fun to style when it' completean app that looks good but doesn' work well is pointless for nowthe home page will display only title and brief description
427
users request pages by entering urls into browser and clicking linksso we'll need to decide what urls are needed in our project the home page url is firstit' the base url people use to access the project at the momentthe base urlsite that lets us know the project was set up correctly we'll change this by mapping the base url to learning log' home page in the main learning_log project folderopen the file urls py here' the code you'll seeurls py from django conf urls import includeurl from django contrib import admin urlpatterns url( '^admin/'include(admin site urls))the first two lines import the functions and modules that manage urls for the project and admin site the body of the file defines the urlpatterns variable in this urls py filewhich represents the project as wholethe urlpatterns variable includes sets of urls from the apps in the project the code at includes the module admin site urlswhich defines all the urls that can be requested from the admin site we need to include the urls for learning_logsfrom django conf urls import includeurl from django contrib import admin urlpatterns url( '^admin/'include(admin site urls)) url( ''include('learning_logs urls'namespace='learning_logs'))we've added line to include the module learning_logs urls at this line includes namespace argumentwhich allows us to distinguish learning_logs' urls from other urls that might appear in the projectwhich can be very helpful as your project starts to grow the default urls py is in the learning_log foldernow we need to make second urls py file in the learning_logs folderurls py """defines url patterns for learning_logs "" from django conf urls import url from import views urlpatterns home page url( '^$'views indexname='index')getting started with django
428
at the beginning of the file we then import the url functionwhich is needed when mapping urls to views we also import the views module wthe dot tells python to import views from the same directory as the current urls py module the variable urlpatterns in this module is list of individual pages that can be requested from the learning_logs app the actual url pattern is call to the url(functionwhich takes three arguments the first is regular expression django will look for regular expression in urlpatterns that matches the requested url string thereforea regular expression will define the pattern that django can look for let' look at the regular expression '^$the tells python to interpret the following string as raw stringand the quotes tell python where the regular expression begins and ends the caret (^tells python to find the beginning of the stringand the dollar sign tells python to look for the end of the string in its entiretythis expression tells python to look for url with nothing between the beginning and end of the url python ignores the base url for the project (empty regular expression matches the base url any other url will not match this expressionand django will return an error page if the url requested doesn' match any existing url patterns the second argument in url(at specifies which view function to call when requested url matches the regular expressiondjango will call views index (we'll write this view function in the next sectionthe third argument provides the name index for this url pattern so we can refer to it in other sections of the code whenever we want to provide link to the home pagewe'll use this name instead of writing out url note regular expressionsoften called regexesare used in almost every programming language they're incredibly usefulbut they take some practice to get used to if you didn' follow all of thisdon' worryyou'll see plenty of examples as you work through this project writing view view function takes in information from requestprepares the data needed to generate pageand then sends the data back to the browseroften by using template that defines what the page will look like the file views py in learning_logs was generated automatically when we ran the command python manage py startapp here' what' in views py right nowviews py from django shortcuts import render create your views here
429
response based on the data provided by views the following code is how the view for the home page should be writtenfrom django shortcuts import render def index(request)"""the home page for learning log""return render(request'learning_logs/index html'when url request matches the pattern we just defineddjango will look for function called index(in the views py file django then passes the request object to this view function in this casewe don' need to process any data for the pageso the only code in the function is call to render(the render(function here uses two arguments--the original request object and template it can use to build the page let' write this template writing template template sets up the structure for web page the template defines what the page should look likeand django fills in the relevant data each time the page is requested template allows you to access any data provided by the view because our view for the home page provided no datathis template is fairly simple inside the learning_logs foldermake new folder called templates inside the templates foldermake another folder called learning_logs this might seem little redundant (we have folder named learning_logs inside folder named templates inside folder named learning_logs)but it sets up structure that django can interpret unambiguouslyeven in the context of large project containing many individual apps inside the inner learning_logs foldermake new file called index html write the following into that fileindex html learning log learning log helps you keep track of your learningfor any topic you're learning about this is very simple file if you're not familiar with htmlthe tags signify paragraphs the tag opens paragraphand the tag closes paragraph we have two paragraphsthe first acts as titleand the second describes what users can do with learning log now when we request the project' base urlwe'll see the page we just built instead of the default django page django will take the requested urland that url will match the pattern '^$'then django will call the function views index()and this will render the page using the template contained in index html the resulting page is shown in figure - getting started with django
430
although it may seem complicated process for creating one pagethis separation between urlsviewsand templates actually works well it allows you to think about each aspect of project separatelyand in larger projects it allows individuals to focus on the areas in which they're strongest for examplea database specialist can focus on the modelsa programmer can focus on the view codeand web designer can focus on the templates try it yourse lf - meal plannerconsider an app that helps people plan their meals throughout the week make new folder called meal_plannerand start new django project inside this folder then make new app called meal_plans make simple home page for this project - pizzeria home pageadd home page to the pizzeria project you started in exercise - (page building additional pages now that we've established routine for building pagewe can start to build out the learning log project we'll build two pages that display dataa page that lists all topics and page that shows all the entries for particular topic for each of these pageswe'll specify url patternwrite view functionand write template but before we do thiswe'll create base template that all templates in the project can inherit from template inheritance when building websiteyou'll almost always require some elements to be repeated on each page rather than writing these elements directly into each pageyou can write base template containing the repeated elements
431
focus on developing the unique aspects of each page and makes it much easier to change the overall look and feel of the project the parent template we'll start by creating template called base html in the same directory as index html this file will contain elements common to all pagesevery other template will inherit from base html the only element we want to repeat on each page right now is the title at the top because we'll include this template on every pagelet' make the title link to the home pagebase html learning log {block content %}{endblock content %the first part of this file creates paragraph containing the name of the projectwhich also acts as link to the home page to generate linkwe use template tagindicated by braces and percent signs {% template tag is bit of code that generates information to be displayed on page in this examplethe template tag {url 'learning_logs:index%generates url matching the url pattern defined in learning_logs/urls py with the name 'indexu in this examplelearning_logs is the namespace and index is uniquely named url pattern in that namespace in simple html pagea link is surrounded by the anchor taglink text having the template tag generate the url for us makes it much easier to keep our links up to date to change url in our projectwe only need to change the url pattern in urls pyand django will automatically insert the updated url the next time the page is requested every page in our project will inherit from base htmlso from now on every page will have link back to the home page at we insert pair of block tags this blocknamed contentis placeholderthe child template will define the kind of information that goes in the content block child template doesn' have to define every block from its parentso you can reserve space in parent templates for as many blocks as you likeand the child template uses only as many as it requires note in python codewe almost always indent four spaces template files tend to have more levels of nesting than python filesso it' common to use only two spaces for each indentation level getting started with django
432
now we need to rewrite index html to inherit from base html here' index htmlindex html {extends "learning_logs/base html% {block content %learning log helps you keep track of your learningfor any topic you're learning about {endblock content %if you compare this to the original index htmlyou can see that we've replaced the learning log title with the code for inheriting from parent template child template must have an {extends %tag on the first line to tell django which parent template to inherit from the file base html is part of learning_logsso we include learning_logs in the path to the parent template this line pulls in everything contained in the base html template and allows index html to define what goes in the space reserved by the content block we define the content block at by inserting {block %tag with the name content everything that we aren' inheriting from the parent template goes inside content block herethat' the paragraph describing the learning log project at we indicate that we're finished defining the content by using an {endblock content %tag you can start to see the benefit of template inheritancein child template we only need to include content that' unique to that page this not only simplifies each templatebut also makes it much easier to modify the site to modify an element common to many pagesyou only need to modify the element in the parent template your changes are then carried over to every page that inherits from that template in project that includes tens or hundreds of pagesthis structure can make it much easier and faster to improve your site note in large projectit' common to have one parent template called base html for the entire site and parent templates for each major section of the site all the section templates inherit from base htmland each page in the site inherits from section template this way you can easily modify the look and feel of the site as wholeany section in the siteor any individual page this configuration provides very efficient way to workand it encourages you to steadily update your site over time the topics page now that we have an efficient approach to building pageswe can focus on our next two pagesthe general topics page and the page to display entries for single topic the topics page will show all topics that users have createdand it' the first page that will involve working with data
433
firstwe define the url for the topics page it' common to choose simple url fragment that reflects the kind of information presented on the page we'll use the word topicsso the url will return this page here' how we modify learning_logs/urls pyurls py """defines url patterns for learning_logs ""--snip-urlpatterns home page url( '^$'views indexname='index')show all topics url( '^topics/$'views topicsname='topics') we've simply added topicsinto the regular expression argument used for the home page url when django examines requested urlthis pattern will match any url that has the base url followed by topics you can include or omit forward slash at the endbut there can' be anything else after the word topicsor the pattern won' match any request with url that matches this pattern will then be passed to the function topics(in views py the topics view the topics(function needs to get some data from the database and send it to the template here' what we need to add to views pyviews py from django shortcuts import render from models import topic def index(request)--snip- def topics(request)"""show all topics "" topics topic objects order_by('date_added' context {'topics'topicsy return render(request'learning_logs/topics html'contextwe first import the model associated with the data we need the topics(function needs one parameterthe request object django received from the server at we query the database by asking for the topic objectssorted by the date_added attribute we store the resulting queryset in topics getting started with django
434
dictionary in which the keys are names we'll use in the template to access the data and the values are the data we need to send to the template in this casethere' one key-value pairwhich contains the set of topics we'll display on the page when building page that uses datawe pass the context variable to render(as well as the request object and the path to the template the topics template the template for the topics page receives the context dictionary so the template can use the data that topics(provides make file called topics html in the same directory as index html here' how we can display the topics in the templatetopics html {extends "learning_logs/base html%{block content %topics {for topic in topics %{topic }{empty %no topics have been added yet {endfor %{endblock content %we start by using the {extends %tag to inherit from base htmljust as the index template doesand then open content block the body of this page contains bulleted list of the topics that have been entered in standard htmla bulleted list is called an unordered listindicated by the tags we begin the bulleted list of topics at at we have another template tag equivalent to for loopwhich loops through the list topics from the context dictionary the code used in templates differs from python in some important ways python uses indentation to indicate which lines of for statement are part of loop in templateevery for loop needs an explicit {endfor %tag indicating where the end of the loop occurs so in templateyou'll see loops written like this{for item in list %do something with each item {endfor %inside the loopwe want to turn each topic into an item in the bulleted list to print variable in templatewrap the variable name in double
435
each pass through the loop the braces won' appear on the pagethey just indicate to django that we're using template variable the html tag indicates list item anything between these tagsinside pair of tagswill appear as bulleted item in the list at we use the {empty %template tagwhich tells django what to do if there are no items in the list in this casewe print message informing the user that no topics have been added yet the last two lines close out the for loop and then close out the bulleted list now we need to modify the base template to include link to the topics pagebase html learning log topics {block content %}{endblock content %we add dash after the link to the home page uand then we add link to the topics pageusing the url template tag again this line tells django to generate link matching the url pattern with the name 'topicsin learning_logs/urls py now when you refresh the home page in your browseryou'll see topics link when you click the linkyou'll see page that looks similar to figure - figure - the topics page individual topic pages nextwe need to create page that can focus on single topicshowing the topic name and all the entries for that topic we'll again define new url patternwrite viewand create template we'll also modify the topics page so each item in the bulleted list links to its corresponding topic page getting started with django
436
the url pattern for the topic page is little different than the other url patterns we've seen so far because it will use the topic' id attribute to indicate which topic was requested for exampleif the user wants to see the detail page for the topic chesswhere the id is the url will be localhost: /topics/ here' pattern to match this urlwhich goes in learning_logs/urls pyurls py --snip-urlpatterns --snip-detail page for single topic url( '^topics/(? \ +)/$'views topicname='topic')let' examine the regular expression in this url patternr'^topics(? \ +)/$the tells django to interpret the string as raw stringand the expression is contained in quotes the second part of the expression/(? \ +)/matches an integer between two forward slashes and stores the integer value in an argument called topic_id the parentheses surrounding this part of the expression captures the value stored in the urlthe ? part stores the matched value in topic_idand the expression \dmatches any number of digits that appear between the forward slashes when django finds url that matches this patternit calls the view function topic(with the value stored in topic_id as an argument we'll use the value of topic_id to get the correct topic inside the function the topic view the topic(function needs to get the topic and all associated entries from the databaseas shown hereviews py --snip- def topic(requesttopic_id)"""show single topic and all its entries "" topic topic objects get(id=topic_idw entries topic entry_set order_by('-date_added' context {'topic'topic'entries'entriesy return render(request'learning_logs/topic html'contextthis is the first view function that requires parameter other than the request object the function accepts the value captured by the expression (? \ +and stores it in topic_id at we use get(to retrieve the topicjust as we did in the django shell at we get the entries associated with this topicand we order them according to date_addedthe minus sign in front of date_added sorts the results in reverse orderwhich will display the most recent entries first we store the topic and entries in the context dictionary and send context to the template topic html
437
for specific information when you're writing queries like these in your own projectsit' very helpful to try them out in the django shell first you'll get much quicker feedback in the shell than you will by writing view and template and then checking the results in browser note the topic template the template needs to display the name of the topic and the entries we also need to inform the user if no entries have been made yet for this topictopic html {extends 'learning_logs/base html%{block content % topic{topic }entries{for entry in entries %{entry date_added|date:' dy : }{entry text|linebreaks }{empty %there are no entries for this topic yet {endfor %{endblock content %we extend base htmlas we do for all pages in the project nextwe show the topic that' currently being displayed uwhich is stored in the template variable {topic }the variable topic is available because it' included in the context dictionary we then start bulleted list to show each of the entries and loop through them as we did the topics earlier each bullet will list two pieces of informationthe timestamp and the full text of each entry for the timestamp xwe display the value of the attribute date_added in django templatesa vertical line (|represents template filter -- function that modifies the value in template variable the filter date:' dy :idisplays timestamps in the format january : the next line displays the full value of text rather than just the first characters from entry the filter linebreaks ensures that long text entries include line breaks in format understood by browsers rather than showing block of uninterrupted text at we use the {empty %template tag to print message informing the user that no entries have been made getting started with django
438
before we look at the topic page in browserwe need to modify the topics template so each topic links to the appropriate page here' the change to topics htmltopics html --snip-{for topic in topics %{topic }{empty %--snip-we use the url template tag to generate the proper linkbased on the url pattern in learning_logs with the name 'topicthis url pattern requires topic_id argumentso we add the attribute topic id to the url template tag now each topic in the list of topics is link to topic pagesuch as if you refresh the topics page and click topicyou should see page that looks like figure - figure - the detail page for single topicshowing all entries for topic try it yourse lf - template documentationskim the django template documentation at when you're working on your own projects - pizzeria pagesadd page to the pizzeria project from exercise - (page that shows the names of available pizzas then link each pizza name to page displaying the pizza' toppings make sure you use template inheritance to build your pages efficiently
439
in this you started learning how to build web applications using the django framework you wrote brief project specinstalled django to virtual environmentlearned to set up projectand checked that the project was set up correctly you learned to set up an app and defined models to represent the data for your app you learned about databases and how django helps you migrate your database after you make change to your models you learned how to create superuser for the admin siteand you used the admin site to enter some initial data you also explored the django shellwhich allows you to work with your project' data in terminal session you learned to define urlscreate view functionsand write templates to make pages for your site finallyyou used template inheritance to simplify the structure of individual templates and to make it easier to modify the site as the project evolves in we'll make intuitiveuser-friendly pages that allow users to add new topics and entries and edit existing entries without going through the admin site we'll also add user registration systemallowing users to create an account and to make their own learning log this is the heart of web app--the ability to create something that any number of users can interact with getting started with django
440
acc at the heart of web application is the ability for any useranywhere in the worldto register an account with your app and start using it in this you'll build forms so users can add their own topics and entriesand edit existing entries you'll also learn how django guards against common attacks to form-based pages so you don' have to spend too much time thinking about securing your apps we'll then implement user authentication system you'll build registration page for users to create accountsand then restrict access to certain pages to logged-in users only we'll then modify some of the view functions so users can only see their own data you'll learn to keep your usersdata safe and secure
441
before we build an authentication system for creating accountswe'll first add some pages that allow users to enter their own data we'll give users the ability to add new topicadd new entryand edit their previous entries currentlyonly superuser can enter data through the admin site we don' want users to interact with the admin siteso we'll use django' formbuilding tools to build pages that allow users to enter data adding new topics let' start by giving users the ability to add new topic adding formbased page works in much the same way as the pages we've already builtwe define urlwrite view functionand write template the one major difference is the addition of new module called forms pywhich will contain the forms the topic modelform any page that lets user enter and submit information on web page is formeven if it doesn' look like one when users enter informationwe need to validate that the information provided is the right kind of data and not anything malicioussuch as code to interrupt our server we then need to process and save valid information to the appropriate place in the database django automates much of this work the simplest way to build form in django is to use modelformwhich uses the information from the models we defined in to automatically build form write your first form in the file forms pywhich you should create in the same directory as models pyforms py from django import forms from models import topic class topicform(forms modelform)class metav model topic fields ['text' labels {'text'''we first import the forms module and the model we'll work withtopic at we define class called topicformwhich inherits from forms modelform the simplest version of modelform consists of nested meta class telling django which model to base the form on and which fields to include in the form at we build form from the topic model and include only the text field the code at tells django not to generate label for the text field
442
the url for new page should be short and descriptiveso when the user wants to add new topicwe'll send them to here' the url pattern for the new_topic pagewhich we add to learning_logsurls pyurls py --snip-urlpatterns --snip-page for adding new topic url( '^new_topic/$'views new_topicname='new_topic')this url pattern will send requests to the view function new_topic()which we'll write next the new_topic(view function the new_topic(function needs to handle two different situationsinitial requests for the new_topic page (in which case it should show blank formand the processing of any data submitted in the form it then needs to redirect the user back to the topics pageviews py from django shortcuts import render from django http import httpresponseredirect from django core urlresolvers import reverse from models import topic from forms import topicform --snip-def new_topic(request)"""add new topic "" if request method !'post'no data submittedcreate blank form form topicform(elsepost data submittedprocess data form topicform(request postx if form is_valid() form save( return httpresponseredirect(reverse('learning_logs:topics')context {'form'formreturn render(request'learning_logs/new_topic html'contextwe import the class httpresponseredirectwhich we'll use to redirect the reader back to the topics page after they submit their topic the reverse(function determines the url from named url patternmeaning that django will generate the url when the page is requested we also import the form we just wrotetopicform user accounts
443
the two main types of request you'll use when building web apps are get requests and post requests you use get requests for pages that only read data from the server you usually use post requests when the user needs to submit information through form we'll be specifying the post method for processing all of our forms ( few other kinds of requests existbut we won' be using them in this project the function new_topic(takes in the request object as parameter when the user initially requests this pagetheir browser will send get request when the user has filled out and submitted the formtheir browser will submit post request depending on the requestwe'll know whether the user is requesting blank form ( get requestor asking us to process completed form ( post requestthe test at determines whether the request method is get or post if the request method is not postthe request is probably getso we need to return blank form (if it' another kind of requestit' still safe to return blank formwe make an instance of topicform vstore it in the variable formand send the form to the template in the context dictionary because we included no arguments when instantiating topicformdjango creates blank form that the user can fill out if the request method is postthe else block runs and processes the data submitted in the form we make an instance of topicform and pass it the data entered by the userstored in request post the form object that' returned contains the information submitted by the user we can' save the submitted information in the database until we've checked that it' valid the is_valid(function checks that all required fields have been filled in (all fields in form are required by defaultand that the data entered matches the field types expected--for examplethat the length of text is less than charactersas we specified in models py in this automatic validation saves us lot of work if everything is validwe can call save(ywhich writes the data from the form to the database once we've saved the datawe can leave this page we use reverse(to get the url for the topics page and pass the url to httpresponseredirect(zwhich redirects the user' browser to the topics page on the topics pagethe user should see the topic they just entered in the list of topics the new_topic template now we make new template called new_topic html to display the form we just creatednew_topic html {extends "learning_logs/base html%{block content %add new topic
444
{csrf_token %{form as_p }add topic {endblock content %this template extends base htmlso it has the same base structure as the rest of the pages in learning log at we define an html form the action argument tells the server where to send the data submitted in the formin this casewe send it back to the view function new_topic(the method argument tells the browser to submit the data as post request django uses the template tag {csrf_token % to prevent attackers from using the form to gain unauthorized access to the server (this kind of attack is called cross-site request forgeryat we display the formhere you see how simple django can make tasks such as displaying form we only need to include the template variable {form as_p }for django to create all the fields necessary to display the form automatically the as_p modifier tells django to render all the form elements in paragraph formatwhich is simple way to display the form neatly django doesn' create submit button for formsso we define one at linking to the new_topic page nextwe include link to the new_topic page on the topics pagetopics html {extends "learning_logs/base html%{block content %topics --snipadd new topic{endblock content %place the link after the list of existing topics figure - shows the resulting form go ahead and use the form to add few new topics of your own user accounts
445
adding new entries now that the user can add new topicthey'll want to add new entries too we'll again define urlwrite view function and templateand link to the page but first we'll add another class to forms py the entry modelform we need to create form associated with the entry modelbut this time with little more customization than topicformforms py from django import forms from models import topicentry class topicform(forms modelform)--snip-class entryform(forms modelform)class metamodel entry fields ['text' labels {'text''' widgets {'text'forms textarea(attrs={'cols' })we first update the import statement to include entry as well as topic the new class entryform inherits from forms modelform and has nested meta class listing the model it' based on and the field to include in the form we again give the field 'texta blank label at we include the widgets attribute widget is an html form elementsuch as single-line text boxmulti-line text areaor drop-down list by including the widgets attribute you can override django' default widget choices by telling django to use forms textarea elementwe're customizing the input widget for the field 'textso the text area will be columns wide instead of the default this will give users enough room to write meaningful entry
446
we need to include topic_id argument in the url for adding new entrybecause the entry must be associated with particular topic here' the urlwhich we add to learning_logs/urls pyurls py --snip-urlpatterns --snip-page for adding new entry url( '^new_entry/(? \ +)/$'views new_entryname='new_entry')this url pattern matches any url with the form : /new_entry/id/where id is number matching the topic id the code (? \ +captures numerical value and stores it in the variable topic_id when url matching this pattern is requesteddjango sends the request and the id of the topic to the new_entry(view function the new_entry(view function the view function for new_entry is much like the function for adding new topicviews py from django shortcuts import render --snip-from models import topic from forms import topicformentryform --snip-def new_entry(requesttopic_id)"""add new entry for particular topic "" topic topic objects get(id=topic_idv if request method !'post'no data submittedcreate blank form form entryform(elsepost data submittedprocess data form entryform(data=request postif form is_valid()new_entry form save(commit=falsenew_entry topic topic new_entry save(return httpresponseredirect(reverse('learning_logs:topic'args=[topic_id])context {'topic'topic'form'formreturn render(request'learning_logs/new_entry html'contextuser accounts
447
the definition of new_entry(has topic_id parameter to store the value it receives from the url we'll need the topic to render the page and process the form' dataso we use topic_id to get the correct topic object at at we check if the request method is post or get the if block executes if it' get requestand we create blank instance of entryform if the request method is postwe process the data by making an instance of entryformpopulated with the post data from the request object we then check if the form is valid if it iswe need to set the entry object' topic attribute before saving it to the database when we call save()we include the argument commit=false to tell django to create new entry object and store it in new_entry without saving it to the database yet we set new_entry' topic attribute to the topic we pulled from the database at the beginning of the function zand then we call save(with no arguments this saves the entry to the database with the correct associated topic at we redirect the user to the topic page the reverse(call requires two arguments--the name of the url pattern we want to generate url for and an args list containing any arguments that need to be included in the url the args list has one item in ittopic_id the httpresponseredirect(call then redirects the user to the topic page they made an entry forand they should see their new entry in the list of entries the new_entry template as you can see in the following codethe template for new_entry is similar to the template for new_topicnew_entry html {extends "learning_logs/base html%{block content % {topic }add new entry{csrf_token %{form as_p }add entry {endblock content %we show the topic at the top of the page uso the user can see which topic they're adding an entry to this also acts as link back to the main page for that topic the form' action argument includes the topic_id value in the urlso the view function can associate the new entry with the correct topic other than thatthis template looks just like new_topic html
448
nextwe need to include link to the new_entry page from each topic pagetopic html {extends "learning_logs/base html%{block content %topic{topic }entriesadd new entry --snip-{endblock content %we add the link just before showing the entriesbecause adding new entry will be the most common action on this page figure - shows the new_entry page now users can add new topics and as many entries as they want for each topic try out the new_entry page by adding few entries to some of the topics you've created figure - the new_entry page editing entries now we'll make page to allow users to edit the entries they've already added user accounts
449
the url for the page needs to pass the id of the entry to be edited here' learning_logs/urls pyurls py --snip-urlpatterns --snip-page for editing an entry url( '^edit_entry/(? \ +)/$'views edit_entryname='edit_entry')the id passed in the url (for exampleedit_entry/ /is stored in the parameter entry_id the url pattern sends requests that match this format to the view function edit_entry(the edit_entry(view function when the edit_entry page receives get requestedit_entry(will return form for editing the entry when the page receives post request with revised entry textit will save the modified text into the databaseviews py from django shortcuts import render --snip-from models import topicentry from forms import topicformentryform --snip-def edit_entry(requestentry_id)"""edit an existing entry "" entry entry objects get(id=entry_idtopic entry topic if request method !'post'initial requestpre-fill form with the current entry form entryform(instance=entryelsepost data submittedprocess data form entryform(instance=entrydata=request postif form is_valid()form save(return httpresponseredirect(reverse('learning_logs:topic'args=[topic id])context {'entry'entry'topic'topic'form'formreturn render(request'learning_logs/edit_entry html'contextwe first need to import the entry model at we get the entry object that the user wants to edit and the topic associated with this entry in the if blockwhich runs for get requestwe make an instance of entryform with
450
form prefilled with information from the existing entry object the user will see their existing data and be able to edit that data when processing post requestwe pass the instance=entry argument and the data=request post argument to tell django to create form instance based on the information associated with the existing entry objectupdated with any relevant data from request post we then check if the form is validif it iswe call save(with no arguments we then redirect to the topic page ywhere the user should see the updated version of the entry they edited the edit_entry template here' edit_entry htmlwhich is similar to new_entry htmledit_entry html {extends "learning_logs/base html%{block content %{topic }edit entryu {csrf_token %{form as_p }save changes {endblock content %at the action argument sends the form back to the edit_entry(function for processing we include the entry id as an argument in the {url %tagso the view function can modify the correct entry object we label the submit button as save changes to remind the user they're saving editsnot creating new entry linking to the edit_entry page now we need to include link to the edit_entry page for each entry on the topic pagetopic html --snip-{for entry in entries %{entry date_added|date:' dy : }{entry text|linebreaks }edit entry --snip-user accounts
451
displayed we use the {url %template tag to determine the url for the named url pattern edit_entryalong with the id attribute of the current entry in the loop (entry idthe link text "edit entryappears after each entry on the page figure - shows what the topic page looks like with these links figure - each entry now has link for editing that entry learning log now has most of the functionality it needs users can add topics and entriesand read through any set of entries they want in the next sectionwe'll implement user registration system so anyone can make an account with learning log and create their own set of topics and entries try it yourse lf - blogstart new django project called blog create an app called blogs in the projectwith model called blogpost the model should have fields like titletextand date_added create superuser for the projectand use the admin site to make couple of short posts make home page that shows all posts in chronological order create form for making new posts and another for editing existing posts fill in your forms to make sure they work
452
in this section we'll set up user registration and authorization system to allow people to register an account and log in and out we'll create new app to contain all the functionality related to working with users we'll also modify the topic model slightly so every topic belongs to certain user the users app we'll start by creating new app called usersusing the startapp command(ll_env)learning_logpython manage py startapp users (ll_env)learning_logls db sqlite learning_log learning_logs ll_env manage py users (ll_env)learning_logls users admin py __init__ py migrations models py tests py views py this command makes new directory called users with structure identical to the learning_logs app adding users to settings py we need to add our new app to installed_apps in settings pylike sosettings py --snip-installed_apps --snip-my apps 'learning_logs''users'--snip-now django will include the users app in the overall project including the urls from users nextwe need to modify the root urls py so it includes the urls we'll write for the users appurls py from django conf urls import includeurl from django contrib import admin urlpatterns url( '^admin/'include(admin site urls))url( '^users/'include('users urls'namespace='users'))url( ''include('learning_logs urls'namespace='learning_logs'))we add line to include the file urls py from users this line will match any url that starts with the word userssuch as user accounts
453
urls that belong to the learning_logs app from urls that belong to the users app the login page we'll first implement login page we'll use the default login view django providesso the url pattern looks little different make new urls py file in the directory learning_log/users/and add the following to iturls py """defines url patterns for users""from django conf urls import url from django contrib auth views import login from import views urlpatterns login page url( '^login/$'login{'template_name''users/login html'}name='login')we first import the default login view the login page' pattern matches the url this urlthe word users tells django to look in users/urls pyand login tells it to send requests to django' default login view (notice the view argument is loginnot views loginbecause we're not writing our own view functionwe pass dictionary telling django where to find the template we're about to write this template will be part of the users appnot the learning_logs app the login template when the user requests the login pagedjango will use its default login viewbut we still need to provide template for the page inside the learning_log/usersdirectorymake directory called templatesinside thatmake another directory called users here' the login html templatewhich you should save in learning_log/users/templates/users/login html {extends "learning_logs/base html%{block content % {if form errors %your username and password didn' match please try again {endif % {csrf_token %{form as_p } log in
454
{endblock content %this template extends base html to ensure that the login page will have the same look and feel as the rest of the site note that template in one app can extend template from another app if the form' errors attribute is setwe display an error message ureporting that the username and password combination don' match anything stored in the database we want the login view to process the formso we set the action argument as the url of the login page the login view sends form to the templateand it' up to us to display the form and add submit button at we include hidden form element'next'the value argument tells django where to redirect the user after they've logged in successfully in this casewe send the user back to the home page linking to the login page let' add the login link to base html so it appears on every page we don' want the link to display when the user is already logged inso we nest it inside an {if %tagbase html learning log topics {if user is_authenticated % hello{user username }{else % log in {endif %{block content %}{endblock content %in django' authentication systemevery template has user variable availablewhich always has an is_authenticated attribute setthe attribute is true if the user is logged in and false if they aren' this allows you to display one message to authenticated users and another to unauthenticated users here we display greeting to users currently logged in authenticated users have an additional username attribute setwhich we use to personalize the greeting and remind the user they're logged in at we display link to the login page for users who haven' been authenticated using the login page we've already set up user accountso let' log in to see if the page works go to for logout link in the header and click it user accounts
455
should see login page similar to the one shown in figure - enter the username and password you set up earlierand you should be brought back to the index page the header on the home page should display greeting personalized with your username figure - the login page logging out now we need to provide way for users to log out we won' build page for logging outusers will just click link and be sent back to the home page we'll define url pattern for the logout linkwrite view functionand provide logout link in base html the logout url the following code defines the url pattern for logging outmatching the url urls py --snip-urlpatterns login page --snip-logout page url( '^logout/$'views logout_viewname='logout')the url pattern sends the request to the logout_view(functionwhich is named as such to distinguish it from the logout(function we'll call from within the view (make sure you're modifying users/urls pynot learning_logurls py the logout_view(view function the logout_view(function is straightforwardwe just import django' logout(functioncall itand then redirect back to the home page open users/views pyand enter the following code
456
from django http import httpresponseredirect from django core urlresolvers import reverse from django contrib auth import logout def logout_view(request)"""log the user out "" logout(requestw return httpresponseredirect(reverse('learning_logs:index')we import the logout(function from django contrib auth in the functionwe call logout(vwhich requires the request object as an argument we then redirect to the home page linking to the logout view now we need logout link we'll include it as part of base html so it' available on every page and include it in the {if user is_authenticated %portion so only users who are already logged in can see itbase html --snip-{if user is_authenticated %hello{user username }log out {else %log in {endif %--snip-figure - shows the current home page as it appears to logged-in user the styling is minimal because we're focusing on building site that works properly when the required set of features workswe'll style the site to look more professional figure - the home page with personalized greeting and logout link the registration page nextwe'll build page to allow new users to register we'll use django' default usercreationform but write our own view function and template user accounts
457
the following code provides the url pattern for the registration pageagain in users/urls pyurls py --snip-urlpatterns login page --snip-registration page url( '^register/$'views registername='register')this pattern matches the url sends requests to the register(function we're about to write the register(view function the register(view function needs to display blank registration form when the registration page is first requested and then process completed registration forms when they're submitted when registration is successfulthe function also needs to log in the new user add the following code to users/views pyviews py from django shortcuts import render from django http import httpresponseredirect from django core urlresolvers import reverse from django contrib auth import loginlogoutauthenticate from django contrib auth forms import usercreationform def logout_view(request)--snip-def register(request)"""register new user ""if request method !'post'display blank registration form form usercreationform(elseprocess completed form form usercreationform(data=request postw if form is_valid()new_user form save(log the user in and then redirect to home page authenticated_user authenticate(username=new_user usernamepassword=request post['password ']login(requestauthenticated_userreturn httpresponseredirect(reverse('learning_logs:index')context {'form'formreturn render(request'users/register html'context
458
authenticate(functions to log in the user if their registration information is correct we also import the default usercreationform in the register(functionwe check whether or not we're responding to post request if we're notwe make an instance of usercreationform with no initial data if we're responding to post requestwe make an instance of usercreationform based on the submitted data we check that the data is valid --in this casethat the username has the appropriate charactersthe passwords matchand the user isn' trying to do anything malicious in their submission if the submitted data is validwe call the form' save(method to save the username and the hash of the password to the database the save(method returns the newly created user objectwhich we store in new_user when the user' information is savedwe log them inwhich is twostep processwe call authenticate(with the arguments new_user username and their password when they registerthe user is asked to enter two matching passwordsand because the form is validwe know the passwords match so we can use either one here we get the value associated with the 'password key in the form' post data if the username and password are correctthe method returns an authenticated user objectwhich we store in authenticated_user we then call the login(function with the request and authenticated_user objects zwhich creates valid session for the new user finallywe redirect the user to the home page where personalized greeting in the header tells them their registration was successful the register template the template for the registration page is similar to the login page be sure to save it in the same directory as login htmlregister html {extends "learning_logs/base html%{block content %{csrf_token %{form as_p }register {endblock content %we use the as_p method again so django will display all the fields in the form appropriatelyincluding any error messages if the form is not filled out correctly user accounts
459
nextwe'll add the code to show the registration page link to any user who is not currently logged inbase html --snip-{if user is_authenticated %hello{user username }log out {else %register log in {endif %--snip-now users who are logged in see personalized greeting and logout link users not logged in see registration page link and login link try out the registration page by making several user accounts with different usernames in the next sectionwe'll restrict some of the pages so they're available only to registered usersand we'll make sure every topic belongs to specific user note the registration system we've set up allows anyone to make any number of accounts for learning log but some systems require users to confirm their identity by sending confirmation email the user must reply to by doing sothe system generates fewer spam accounts than the simple system we're using here howeverwhen you're learning to build appsit' perfectly appropriate to practice with simple user registration system like the one we're using try it yourse lf - blog accountsadd user authentication and registration system to the blog project you started in exercise - (page make sure logged-in users see their username somewhere on the screen and unregistered users see link to the registration page allowing users to own their data users should be able to enter data exclusive to themso we'll create system to figure out which data belongs to which userand then we'll restrict access to certain pages so users can work with only their own data in this sectionwe'll modify the topic model so every topic belongs to specific user this will also take care of entriesbecause every entry belongs to specific topic we'll start by restricting access to certain pages
460
django makes it easy to restrict access to certain pages to logged-in users through the @login_required decorator decorator is directive placed just before function definition that python applies to the function before it runs to alter how the function code behaves let' look at an example restricting access to the topics page each topic will be owned by userso only registered users should be able to request the topics page add the following code to learning_logs/views pyviews py --snip-from django core urlresolvers import reverse from django contrib auth decorators import login_required from models import topicentry --snip-@login_required def topics(request)"""show all topics ""--snip-we first import the login_required(function we apply login_required(as decorator to the topics(view function by prepending login_required with the symbol so python knows to run the code in login_required(before the code in topics(the code in login_required(checks to see if user is logged inand django will run the code in topics(only if they are if the user is not logged inthey're redirected to the login page to make this redirect workwe need to modify settings py so django knows where to find the login page add the following at the very end of settings pysettings py ""django settings for learning_log project --snip-my settings login_url '/users/login/now when an unauthenticated user requests page protected by the @login_required decoratordjango will send the user to the url defined by login_url in settings py you can test this setting by logging out of any user accounts and going to the home page nextclick the topics linkwhich should redirect you to the login page then log in to any of your accountsand from the home page click the topics link again you should be able to reach the topics page user accounts
461
django makes it easy to restrict access to pagesbut you have to decide which pages to protect it' better to think about which pages need to be unrestricted first and then restrict all the other pages in the project you can easily correct overrestricting accessand it' less dangerous than leaving sensitive pages unrestricted in learning logwe'll keep the home pagethe registration pageand logout unrestricted we'll restrict access to every other page here' learning_logs/views py with @login_required decorators applied to every view except index()views py --snip-@login_required def topics(request)--snip-@login_required def topic(requesttopic_id)--snip-@login_required def new_topic(request)--snip-@login_required def new_entry(requesttopic_id)--snip-@login_required def edit_entry(requestentry_id)--snip-try accessing each of these pages while logged outyou'll be redirected back to the login page you'll also be unable to click links to pages such as new_topic but if you enter the url redirected to the login page you should restrict access to any url that' publicly accessible and relates to private user data connecting data to certain users now we need to connect the data submitted to the user who submitted it we need to connect only the data highest in the hierarchy to userand the lower-level data will follow for examplein learning logtopics are the highest level of data in the appand all entries are connected to topic as long as each topic belongs to specific userwe'll be able to trace the ownership of each entry in the database we'll modify the topic model by adding foreign key relationship to user we'll then have to migrate the database finallywe'll have to modify some of the views so they only show the data associated with the currently logged-in user
462
the modification to models py is just two linesmodels py from django db import models from django contrib auth models import user class topic(models model)""" topic the user is learning about""text models charfield(max_length= date_added models datetimefield(auto_now_add=trueowner models foreignkey(userdef __str__(self)"""return string representation of the model ""return self text class entry(models model)--snip-we first import the user model from django contrib auth we then add an owner field to topicwhich establishes foreign key relationship to the user model identifying existing users when we migrate the databasedjango will modify the database so it can store connection between each topic and user to make the migrationdjango needs to know which user to associate with each existing topic the simplest approach is to give all existing topics to one user--for examplethe superuser firstwe need to know the id of that user let' look at the ids of all users created so far start django shell session and issue the following commands(venv)learning_logpython manage py shell from django contrib auth models import user user objects all([ for user in user objects all()print(user usernameuser idll_admin eric willie at we import the user model into the shell session we then look at all the users that have been created so far the output shows three usersll_adminericand willie at we loop through the list of users and print each user' username and id when django asks which user to associate the existing topics withwe'll use one of these id values user accounts
463
now that we know the idswe can migrate the database (venv)learning_logpython manage py makemigrations learning_logs you are trying to add non-nullable field 'ownerto topic without defaultwe can' do that (the database needs something to populate existing rowsw please select fix provide one-off default now (will be set on all existing rows quitand let me add default in models py select an option please enter the default value nowas valid python the datetime and django utils timezone modules are availableso you can do timezone now( migrations for 'learning_logs' _topic_owner pyadd field owner to topic we start by issuing the makemigrations command in the output at vdjango indicates that we're trying to add required (non-nullablefield to an existing model (topicwith no default value specified django gives us two options at wwe can provide default right nowor we can quit and add default value in models py at we've chosen the first option django then asks us to enter the default value to associate all existing topics with the original admin userll_admini entered the user id of at you can use the id of any user you've createdit doesn' have to be superuser django then migrates the database using this value and generates the migration file _topic_owner pywhich adds the field owner to the topic model now we can carry out the migration enter the following in an active virtual environment(venv)learning_logpython manage py migrate operations to performsynchronize unmigrated appsmessagesstaticfiles apply all migrationslearning_logscontenttypessessionsadminauth --snip-running migrationsrendering model states done applying learning_logs _topic_owner ok (venv)learning_logdjango applies the new migrationand the result is ok we can verify that the migration worked as expected in the shell sessionlike thisu from learning_logs models import topic for topic in topic objects all()print(topictopic owner
464
chess ll_admin rock climbing ll_admin we import topic from learning_logs models and then loop through all existing topicsprinting each topic and the user it belongs to you can see that each topic now belongs to the user ll_admin note you can simply reset the database instead of migratingbut that will lose all existing data it' good practice to learn how to migrate database while maintaining the integrity of usersdata if you do want to start with fresh databaseissue the command python manage py flush to rebuild the database structure you'll have to create new superuserand all of your data will be gone restricting topics access to appropriate users currentlyif you're logged inyou'll be able to see all the topicsno matter which user you're logged in as we'll change that by showing users only the topics that belong to them make the following change to the topics(function in views pyviews py --snip-@login_required def topics(request)"""show all topics ""topics topic objects filter(owner=request userorder_by('date_added'context {'topics'topicsreturn render(request'learning_logs/topics html'context--snip-when user is logged inthe request object has request user attribute set that stores information about the user the code fragment topic objects filter(owner=request usertells django to retrieve only the topic objects from the database whose owner attribute matches the current user because we're not changing how the topics are displayedwe don' need to change the template for the topics page at all to see if this workslog in as the user you connected all existing topics toand go to the topics page you should see all the topics now log outand log back in as different user the topics page should list no topics protecting user' topics we haven' actually restricted access to the topic pages yetso any registered user could try bunch of urlslike and retrieve topic pages that happen to match try it yourself while logged in as the user that owns all topicscopy the url or note the id in the url of topicand then log out and log back in user accounts
465
the entrieseven though you're logged in as different user we'll fix this now by performing check before retrieving the requested entries in the topic(view functionviews py from django shortcuts import render from django http import httpresponseredirecthttp from django core urlresolvers import reverse --snip-@login_required def topic(requesttopic_id)"""show single topic and all its entries ""topic topic objects get(id=topic_idmake sure the topic belongs to the current user if topic owner !request userraise http entries topic entry_set order_by('-date_added'context {'topic'topic'entries'entriesreturn render(request'learning_logs/topic html'context--snip- response is standard error response that' returned when requested resource doesn' exist on server here we import the http exception uwhich we'll raise if the user requests topic they shouldn' see after receiving topic requestwe make sure the topic' user matches the currently logged-in user before rendering the page if the current user doesn' own the requested topicwe raise the http exception vand django returns error page now if you try to view another user' topic entriesyou'll see page not found message from django in we'll configure the project so users will see proper error page protecting the edit_entry page the edit_entry pages have urls in the form entry_id/where the entry_id is number let' protect this page so no one can use the url to gain access to someone else' entriesviews py --snip-@login_required def edit_entry(requestentry_id)"""edit an existing entry ""entry entry objects get(id=entry_idtopic entry topic if topic owner !request userraise http
466
initial requestpre-fill form with the current entry --snip-we retrieve the entry and the topic associated with this entry we then check if the owner of the topic matches the currently logged-in userif they don' matchwe raise an http exception associating new topics with the current user currentlyour page for adding new topics is brokenbecause it doesn' associate new topics with any particular user if you try adding new topicyou'll see the error message integrityerror along with learning_logs_topic user_id may not be null django' saying you can' create new topic without specifying value for the topic' owner field there' straightforward fix for this problembecause we have access to the current user through the request object add the following codewhich associates the new topic with the current userviews py --snip-@login_required def new_topic(request)"""add new topic ""if request method !'post'no data submittedcreate blank form form topicform(elsepost data submittedprocess data form topicform(request postif form is_valid() new_topic form save(commit=falsev new_topic owner request user new_topic save(return httpresponseredirect(reverse('learning_logs:topics')context {'form'formreturn render(request'learning_logs/new_topic html'context--snip-when we first call form save()we pass the commit=false argument because we need to modify the new topic before saving it to the database we then set the new topic' owner attribute to the current user finallywe call save(on the topic instance just defined now the topic has all the required data and will save successfully you should be able to add as many new topics as you want for as many different users as you want each user will have access only to their own datawhether they're viewing dataentering new dataor modifying old data user accounts
467
- refactoringthere are two places in views py where we make sure the user associated with topic matches the currently logged-in user put the code for this check in function called check_topic_owner()and call this function where appropriate - protecting new_entrya user can add new entry to another user' learning log by entering url with the id of topic belonging to another user prevent this attack by checking that the current user owns the entry' topic before saving the new entry - protected blogin your blog projectmake sure each blog post is connected to particular user make sure all posts are publicly accessible but only registered users can add posts and edit existing posts in the view that allows users to edit their postsmake sure the user is editing their own post before processing the form summary in this you learned to use forms to allow users to add new topics and entriesand edit existing entries you then learned how to implement user accounts you allowed existing users to log in and outand you learned how to use django' default usercreationform to let people create new accounts after building simple user authentication and registration systemyou restricted access to logged-in users for certain pages using the @login_ required decorator you then attributed data to specific users through foreign key relationship you also learned to migrate the database when the migration requires you to specify some default data finallyyou learned how to make sure user can see only data that belongs to them by modifying the view functions you retrieved appropriate data using the filter(methodand you learned to compare the owner of the requested data to the currently logged-in user it may not always be immediately obvious what data you should make available and what data you should protectbut this skill will come with practice the decisions we've made in this to secure our usersdata illustrate why working with others is good idea when building projecthaving someone else look over your project makes it more likely that you'll spot vulnerable areas we now have fully functioning project running on our local machine in the final we'll style learning log to make it visually appealingand we'll deploy the project to server so anyone with internet access can register and make an account
468
app learning log is fully functional nowbut it has no styling and runs only on your local machine in this we'll style the project in simple but professional manner and then deploy it to live server so anyone in the world can make an account for the styling we'll use the bootstrap librarya collection of tools for styling web applications so they look professional on all modern devicesfrom large flat-screen monitor to smartphone to do thiswe'll use the django-bootstrap appwhich will also give you practice using apps made by other django developers we'll deploy learning log using herokua site that lets you push your project to one of its serversmaking it available to anyone with an internet connection we'll also start using version control system called git to track changes to the project
469
simple web applicationsmake them look goodand deploy them to live server you'll also be able to use more advanced learning resources as you develop your skills styling learning log we've purposely ignored styling until now to focus on learning log' functionality first this is good way to approach developmentbecause an app is useful only if it works of courseonce it' workingappearance is critical so people will want to use it in this section 'll introduce the django-bootstrap app and show you how to integrate it into project to make it ready for live deployment the django-bootstrap app we'll use django-bootstrap to integrate bootstrap into our project this app downloads the required bootstrap filesplaces them in an appropriate location in your projectand makes the styling directives available in your project' templates to install django-bootstrap issue the following command in an active virtual environment(ll_env)learning_logpip install django-bootstrap --snip-successfully installed django-bootstrap nextwe need to add the following code to include django-boostrap in installed_apps in settings pysettings py --snip-installed_apps --snip-'django contrib staticfiles'third party apps 'bootstrap 'my apps 'learning_logs''users'--snip-start new section called third party apps for apps created by other developers and add 'bootstrap to this section most apps need to be included in installed_appsbut to be sureread the setup instructions for the particular app you're using
470
enables some of the interactive elements that the bootstrap template provides add this code to the end of settings pysettings py --snip-my settings login_url '/users/login/settings for django-bootstrap bootstrap 'include_jquery'truethis code spares us from having to download jquery and place it in the correct location manually using bootstrap to style learning log bootstrap is basically large collection of styling tools it also has number of templates you can apply to your project to create particular overall style if you're just starting outit' much easier to use these templates than it is to use individual styling tools to see the templates bootstrap offersgo to the getting started section at to the examples headingand look for the navbars in action section we'll use the static top navbar templatewhich provides simple top navigation bara page headerand container for the content of the page figure - shows what the home page will look like after we apply bootstrap' template to base html and modify index html slightly figure - the learning log home page using bootstrap styling and deploying an app
471
easier to understand modifying base html we need to modify the base html template to accommodate the bootstrap template 'll introduce the new base html in parts defining the html headers the first change to base html defines the html headers in the file so whenever learning log page is openthe browser title bar displays the site name we'll also add some requirements for using bootstrap in our templates delete everything in base html and replace it with the following codebase html {load bootstrap % learning log {bootstrap_css %{bootstrap_javascript %at we load the collection of template tags available in djangobootstrap nextwe declare this file as an html document written in english an html file is divided into two main partsthe head and the body--the head of the file begins at the head of an html file doesn' contain any contentit just tells the browser what it needs to know to display the page correctly at we include title element for the pagewhich will be displayed in the title bar of the browser whenever learning log is open at we use one of django-bootstrap ' custom template tagswhich tells django to include all the bootstrap style files the tag that follows enables all the interactive behavior you might use on pagesuch as collapsible navigation bars at is the closing tag defining the navigation bar now we'll define the navigation bar at the top of the page--snip
472
<button type="buttonclass="navbar-toggle collapseddata-toggle="collapsedata-target="#navbararia-expanded="falsearia-controls="navbar"learning log topics {if user is_authenticated %hello{user username }log out {else %register log in {endif %the first element is the opening tag the body of an html file contains the content users will see on page at is element that indicates the navigation links section of the page everything contained in this element is styled according to the bootstrap style rules defined by the selectors navbarnavbar-defaultand navbar-static-top selector determines which elements on page certain style rule applies to at the template defines button that will appear if the browser window is too narrow to display the whole navigation bar horizontally when the user clicks the buttonthe navigation elements will appear in dropdown list the collapse reference causes the navigation bar to collapse when the user shrinks the browser window or when the site is displayed on mobile devices with small screens at we set the project' name to appear at the far left of the navigation bar and make it link to the home pagebecause it will appear on every page in the project at we define set of links that lets users navigate the site navigation bar is basically list that starts with yand each link is an item in this list ( to add more linksinsert more lines using the following structuretitle styling and deploying an app
473
directly from the previous version of base html at we place second list of navigation linksthis time using the selector navbar-right the navbar-right selector styles the set of links so it appears at the right edge of the navigation bar where you typically see login and registration links here we'll display the user greeting and logout link or links to register or log in the rest of the code in this section closes out the elements that contain the navigation bar defining the main part of the page the rest of base html contains the main part of the page--snipu {block header %}{endblock header %{block content %}{endblock content %at is an opening div with the class container div is section of web page that can be used for any purpose and can be styled with borderspace around the element (margins)space between the contents and the border (padding)background colorsand other style rules this particular div acts as container into which we place two elementsa new block called header and the content block we used in the header block contains information telling the user what kind of information the page holds and what they can do on page it has the class page-headerwhich applies set of style rules to the block the content block is in separate div with no specific style classes when you load the home page of learning log in browseryou should see professional-looking navigation bar that matches the one shown in figure - try resizing the window so it' really narrowthe navigation bar should be replaced by button click the buttonand all the links should appear in drop-down list note this simplified version of the bootstrap template should work on most recent browsers earlier browsers may not render some styles correctly the full templateavailable at available browsers
474
let' update the home page using the newly defined header block and another bootstrap element called jumbotron-- large box that will stand out from the rest of the page and can contain anything you want it' typically used on home pages to hold brief description of the overall project while we're at itwe'll update the message on the home page as well here' index htmlindex html {extends "learning_logs/base html% {block header % track your learning {endblock header % {block content %register an account to make your own learning logand list the topics you're learning about whenever you learn something new about topicmake an entry summarizing what you've learned {endblock content %at we tell django that we're about to define what goes in the header block inside jumbotron element we place short taglinetrack your learningto give first-time visitors sense of what learning log does at we add text to provide little more direction we invite people to make an accountand we describe the two main actions--add new topics and make topic entries the index page now looks like figure - and is significant improvement over our unstyled project styling the login page we've refined the overall appearance of the login page but not the login form yetso let' make the form look consistent with the rest of the pagelogin html {extends "learning_logs/base html% {load bootstrap % {block header %log in to your account {endblock header %{block content % {csrf_token %styling and deploying an app
475
{bootstrap_form form % {buttons %log in {endbuttons %{endblock content %at we load the bootstrap template tags into this template at we define the header blockwhich describes what the page is for notice that we've removed the {if form errors %block from the templatedjangobootstrap manages form errors automatically at we add class="formattributeand then we use the template tag {bootstrap_form %when we display the form xthis replaces the {form as_p }tag we were using in the {booststrap_form %template tag inserts bootstrap style rules into the individual elements of the form as it' rendered at we open bootstrap template tag {buttons %}which adds bootstrap styling to buttons figure - shows the login form as it' rendered now the page is much cleaner and has consistent styling and clear purpose try logging in with an incorrect username or passwordyou'll see that even the error messages are styled consistently and integrate well with the overall site figure - the login page styled with bootstrap
476
let' make the rest of the pages look consistent as well we'll update the new_topic page nextnew_topic html {extends "learning_logs/base html%{load bootstrap % {block header %add new topic{endblock header %{block content % <form action="{url 'learning_logs:new_topic%}method='postclass="form"{csrf_token %{bootstrap_form form %{buttons %add topic {endbuttons %{endblock content %most of the changes here are similar to those applied in login htmlwe load bootstrap and add the header block with an appropriate message at then we add the class="formattribute to the tag vuse the {bootstrap_form %template tag instead of {form as_p }wand use the bootstrap structure for the submit button log in and navigate to the new_topic pageit should look similar to the login page now styling the topics page now let' make sure the pages for viewing information are styled appropriately as wellstarting with the topics pagetopics html {extends "learning_logs/base html% {block header %topics {endblock header %{block content %{for topic in topics %styling and deploying an app
477
{topic }{empty %no topics have been added yet {endfor % add new topic {endblock content %we don' need the {load bootstrap %tagbecause we're not using any custom bootstrap template tags in this file we add the heading topics inside the header block we style each topic as an element to make them little larger on the page and do the same for the link to add new topic styling the entries on the topic page the topic page has more content than most pagesso it needs bit more work we'll use bootstrap' panels to make each entry stand out panel is div with predefined styling and is perfect for displaying topic' entriestopic html {extends 'learning_logs/base html% {block header %{topic }{endblock header %{block content %add new entry {for entry in entries %{entry date_added|date:' dy : }edit entry {entry text|linebreaks }
478
there are no entries for this topic yet {endfor %{endblock content %we first place the topic in the header block we then delete the unordered list structure previously used in this template instead of making each entry list itemwe create panel div element at vwhich contains two more nested divsa panel-heading div and panel-body div the panel-heading div contains the date for the entry and the link to edit the entry both are styled as elements xbut we add tags around the edit_entry link to make it little smaller than the timestamp at is the panel-body divwhich contains the actual text of the entry notice that the django code for including the information on the page hasn' changed at allonly the elements that affect the appearance of the page have changed figure - shows the topic page with its new look the functionality of learning log hasn' changedbut it looks more professional and inviting to users figure - the topic page with bootstrap styling note if you want to use different bootstrap templatefollow similar process to what we've done so far in this copy the template into base htmland modify the elements that contain actual content so the template displays your project' information then use bootstrap' individual styling tools to style the content on each page styling and deploying an app
479
- other formswe've applied bootstrap' styles to the login and add_topic pages make similar changes to the rest of the form-based pagesnew_entry and edit_entryand register - stylish bloguse bootstrap to style the blog project you created in deploying learning log now that we have professional-looking projectlet' deploy it to live server so anyone with an internet connection can use it we'll use herokua web-based platform that allows you to manage the deployment of web applications we'll get learning log up and running on heroku the process is slightly different on windows than it is on linux and os if you're using windowscheck for notes in each section that specify what you'll need to do differently on your system making heroku account to make an accountgo to links it' free to make an accountand heroku has free tier that allows you to test your projects in live deployment note heroku' free tier has limitssuch as the number of apps you can deploy and how often people can visit your app but these limits are generous enough to let you practice deploying apps without any cost installing the heroku toolbelt to deploy and manage project on heroku' serversyou'll need the tools available in the heroku toolbelt to install the latest version of the heroku toolbeltvisit operating systemwhich will include either one-line terminal command or an installer you can download and run installing required packages you'll also need to install number of packages that help serve django projects on live server in an active virtual environmentissue the following commands(ll_env)learning_logpip install dj-database-url (ll_env)learning_logpip install dj-static (ll_env)learning_logpip install static (ll_env)learning_logpip install gunicorn
480
package fails to install correctly the package dj-database-url helps django communicate with the database heroku usesdj-static and static help django manage static files correctlyand gunicorn is server capable of serving apps in live environment (static files contain style rules and javascript files note some of the required packages may not install on windowsso don' be concerned if you get an error message when you try to install some of them what matters is getting heroku to install the packages on the live deploymentand we'll do that in the next section creating packages list with requirements txt file heroku needs to know which packages our project depends onso we'll use pip to generate file listing them againfrom an active virtual environmentissue the following command(ll_env)learning_logpip freeze requirements txt the freeze command tells pip to write the names of all the packages currently installed in the project into the file requirements txt open requirements txt to see the packages and version numbers installed in your project (windows users might not see all of these lines)requirements txt django=dj-database-url=dj-static=django-bootstrap =gunicorn=static =learning log already depends on six different packages with specific version numbersso it requires specific environment to run properly when we deploy learning logheroku will install all the packages listed in requirements txtcreating an environment with the same packages we're using locally for this reasonwe can be confident the deployed project will behave the same as it does on our local system this is huge advantage as you start to build and maintain various projects on your system nextwe need to add psycopg which helps heroku manage the live databaseto the list of packages open requirements txt and add the line psycopg >this will install version of psycopg or newer version if it' availablerequirements txt django=dj-database-url=dj-static=django-bootstrap =gunicorn=styling and deploying an app
481
psycopg >if any of the packages didn' install on your systemadd those as well when you're finishedyour requirements txt file should include each of the packages shown above if package is listed on your system but the version number differs from what' shown herekeep the version you have on your system note if you're using windowsmake sure your version of requirements txt matches the list shown here regardless of which packages you were able to install on your system specifying the python runtime unless you specify python versionheroku will use its own current default version of python let' make sure heroku uses the same version of python we're using in an active virtual environmentissue the command python --version(ll_env)learning_logpython --version python in this example ' running python make new file called runtime txt in the same directory as manage pyand enter the followingruntime txt pythonthis file should contain one line with your python version specified in the format shownmake sure you enter python in lowercasefollowed by hyphenfollowed by the three-part version number note if you get an error reporting that the python runtime you requested is not availablego to specifying python runtime scan through the article to find the available runtimesand use the one that most closely matches your python version modifying settings py for heroku now we need to add section at the end of settings py to define some settings specifically for the heroku environmentsettings py --snip-settings for django-bootstrap bootstrap 'include_jquery'true
482
if os getcwd(='/app' import dj_database_url databases 'default'dj_database_url config(default='postgres://localhost' honor the ' -forwarded-protoheader for request is_secure(secure_proxy_ssl_header ('http_x_forwarded_proto''https' allow all host headers allowed_hosts ['*' static asset configuration base_dir os path dirname(os path abspath(__file__)static_root 'staticfilesstaticfiles_dirs os path join(base_dir'static')at we use the function getcwd()which gets the current working directory the file is running from in heroku deploymentthe directory is always /app in local deploymentthe directory is usually the name of the project folder (learning_log in our casethe if test ensures that the settings in this block apply only when the project is deployed on heroku this structure allows us to have one settings file that works for our local development environment as well as the live server at we import dj_database_url to help configure the database on heroku heroku uses postgresql (also called postgres) more advanced database than sqliteand these settings configure the project to use postgres on heroku the rest of the settings support https requests wensure that django will serve the project from heroku' url xand set up the project to serve static files correctly on heroku making procfile to start processes procfile tells heroku which processes to start in order to serve the project properly this is one-line file that you should save as procfilewith an uppercase and no file extensionin the same directory as manage py here' what goes in procfileprocfile webgunicorn learning_log wsgi --log-file this line tells heroku to use gunicorn as server and to use the settings in learning_log/wsgi py to launch the app the log-file flag tells heroku the kinds of events to log styling and deploying an app
483
we also need to modify wsgi py for herokubecause heroku needs slightly different setup than what we've been usingwsgi py --snip-import os from django core wsgi import get_wsgi_application from dj_static import cling os environ setdefault("django_settings_module""learning_log settings"application cling(get_wsgi_application()we import clingwhich helps serve static files correctlyand use it to launch the application this code will work locally as wellso we don' need to put it in an if block making directory for static files on herokudjango collects all the static files and places them in one place so it can manage them efficiently we'll create directory for these static files inside the learning_log folder we've been working from is another folder called learning_log in this nested foldermake new folder called static with the path learning_log/learning_log/staticwe also need to make placeholder file to store in this directory for nowbecause empty directories won' be included in the project when it' pushed to heroku in the staticdirectorymake file called placeholder txtplaceholder txt this file ensures that learning_log/staticwill be added to the project django will collect static files and place them in learning_log/staticthere' nothing special about this textit just reminds us why we included this file in the project using the gunicorn server locally if you're using linux or os xyou can try using the gunicorn server locally before deploying to heroku from an active virtual environmentrun the command heroku local to start the processes defined in procfile(ll_env)learning_logheroku local installing heroku toolbelt done --snip-forego starting web on port web : : - [ [infostarting gunicorn web : : - [ [infolistening atw web : : - [ [infobooting worker with pid
484
heroku toolbelt will be installed the output shows that gunicorn has been started with process id of in this example at gunicorn is listening for requests on port in additiongunicorn has started worker process ( to help it serve requests visit should see the learning log home pagejust as it appears when you use the django server (runserverpress ctrl- to stop the processes started by heroku local you should continue to use runserver for local development note gunicorn won' run on windowsso skip this step if you're using windows this won' affect your ability to deploy the project to heroku using git to track the project' files if you completed you'll know that git is version control program that allows you to take snapshot of the code in your project each time you implement new feature successfully this allows you to easily return to the last working snapshot of your project if anything goes wrongfor exampleif you accidentally introduce bug while working on new feature each of these snapshots is called commit using git means you can try implementing new features without worrying about breaking your project when you're deploying to live serveryou need to make sure you're deploying working version of your project if you want to read more about git and version controlsee appendix installing git the heroku toolbelt includes gitso it should already be installed on your system but terminal windows that were open before you installed the heroku toolbelt won' have access to gitso open new terminal window and issue the command git --version(ll_env)learning_loggit --version git version if you get an error message for some reasonsee the instructions in appendix for installing git configuring git git keeps track of who makes changes to projecteven in cases like this when there' only one person working on the project to do thisgit needs to know your username and email you have to provide usernamebut feel free to make up an email for your practice projects(ll_env)learning_loggit config --global user name "ehmatthes(ll_env)learning_loggit config --global user email "eric@example comstyling and deploying an app
485
you make your first commit ignoring files we don' need git to track every file in the projectso we'll tell git to ignore some files make file called gitignore in the folder that contains manage py notice that this filename begins with dot and has no file extension here' what goes in gitignoregitignore ll_env__pycache__sqlite we tell git to ignore the entire directory ll_envbecause we can re-create it automatically at any time we also don' track the __pycache__ directorywhich contains the pyc files that are created automatically when django runs the py files we don' track changes to the local databasebecause it' bad habitif you're ever using sqlite on serveryou might accidentally overwrite the live database with your local test database when you push the project to the server note if you're using python replace __pycache__ with pyc because python doesn' create __pycache__ directory committing the project we need to initialize git repository for learning logadd all the necessary files to the repositoryand commit the initial state of the project here' how we do thatu (ll_env)learning_loggit init initialized empty git repository in /home/ehmatthes/pcc/learning_loggitv (ll_env)learning_loggit add (ll_env)learning_loggit commit -am "ready for deployment to heroku [master (root-commitdbc ready for deployment to heroku files changed insertions(+create mode gitignore create mode procfile --snip-create mode users/views py (ll_env)learning_loggit status on branch master nothing to commitworking directory clean (ll_env)learning_logat we issue the git init command to initialize an empty repository in the directory containing learning log at we use the git add commandwhich adds all the files that aren' being ignored to the repository (don' forget the dot at we issue the command git commit -am commit messagethe - flag tells git to include all changed files in this commitand the - flag tells git to record log message
486
branch and that our working directory is clean this is the status you'll want to see any time you push your project to heroku pushing to heroku we're finally ready to push the project to heroku in an active terminal sessionissue the following commandsu (ll_env)learning_logheroku login enter your heroku credentials emaileric@example com password (typing will be hidden)logged in as eric@example com (ll_env)learning_logheroku create creating afternoon-meadow- donestack is cedar- git remote heroku added (ll_env)learning_loggit push heroku master --snip-remotelaunching donev remoteremoteverifying deploy done to bdb master -master (ll_env)learning_logfirstlog in to heroku in the terminal session with the username and password you used to create an account at heroku to build an empty project heroku generates name made up of two words and numberyou can change this later on we then issue the command git push heroku master wwhich tells git to push the master branch of the project to the repository heroku just created heroku then builds the project on its servers using these files at is the url we'll use to access the live project when you've issued these commandsthe project is deployed but not fully configured to check that the server process started correctlyuse the heroku ps command(ll_env)learning_logheroku ps free quota left ==web (free)`gunicorn learning_log wsgi __log-file -web up : : ( ago(ll_env)learning_logthe output shows how much more time the project can be active in the next hours at the time of this writingheroku allows free deployments to be active for up to hours in any -hour period if project styling and deploying an app
487
customize this error page shortly at we see that the process defined in procfile has been started now we can open the app in browser using the command heroku open(ll_env)learning_logheroku open opening afternoon-meadow- done this command spares you from opening browser and entering the url heroku showed youbut that' another way to open the site you should see the home page for learning logstyled correctly howeveryou can' use the app yet because we haven' set up the database note heroku' deployment process changes from time to time if you have any issues you can' resolvelook at heroku' documentation for help go to heroku com/click pythonand look for link to getting started with django if you can' understand what you see therecheck out the suggestions in appendix setting up the database on heroku we need to run migrate once to set up the live database and apply all the migrations we generated during development you can run django and python commands on heroku project using the command heroku run here' how to run migrate on the heroku deploymentu (ll_env)learning_logheroku run python manage py migrate running `python manage py migrateon afternoon-meadow- uprun --snip- running migrations--snip-applying learning_logs _initial ok applying learning_logs _entry ok applying learning_logs _topic_user ok applying sessions _initial ok (ll_env)learning_logwe first issue the command heroku run python manage py migrate heroku then creates terminal session to run the migrate command at django applies the default migrations and the migrations we generated during the development of learning log now when you visit your deployed appyou should be able to use it just as you did on your local system howeveryou won' see any of the data you entered on your local deploymentbecause we didn' copy the data to the live server this is normal practiceyou don' usually copy local data to live deployment because the local data is usually test data you can share your heroku link to let anyone use your version of learning log in the next section we'll complete few more tasks to finish the deployment process and set you up to continue developing learning log
488
in this section we'll refine the deployment by creating superuserjust as we did locally we'll also make the project more secure by changing the setting debug to falseso users won' see any extra information in error messages that they could use to attack the server creating superuser on heroku you've already seen that we can run one-off commands using the heroku run command but you can also run commands by opening bash terminal session while connected to the heroku server using the command heroku run bash bash is the language that runs in many linux terminals we'll use the bash terminal session to create superuser so we can access the admin site on the live app(ll_env)learning_logheroku run bash running `bashon afternoon-meadow- uprun ls learning_log learning_logs manage py procfile requirements txt runtime txt users staticfiles python manage py createsuperuser username (leave blank to use ' ')ll_admin email addresspasswordpassword (again)superuser created successfully exit exit (ll_env)learning_logat we run ls to see which files and directories exist on the serverwhich should be the same files we have on our local system you can navigate this file system like any other note windows users will use the same commands shown here (such as ls instead of dir)because you're running linux terminal through remote connection at we run the command to create superuserwhich outputs the same prompts we saw on our local system when we created superuser in when you're finished creating the superuser in this terminal sessionuse the exit command to return to your local system' terminal session now you can add /adminto the end of the url for the live app and log in to the admin site for methe url is herokuapp com/adminif other people have already started using your projectbe aware that you'll have access to all of their datadon' take this lightlyand users will continue to trust you with their data styling and deploying an app
489
you'll probably want your url to be friendlier and more memorable than single command(ll_env)learning_logheroku apps:rename learning-log renaming afternoon-meadow- to learning-log done git remote heroku updated (ll_env)learning_logyou can use lettersnumbersand dashes when naming your appand call it whatever you wantas long as no one else has claimed the name this deployment now lives at longer available at the previous urlthe apps:rename command completely moves the project to the new url when you deploy your project using heroku' free serviceheroku puts your deployment to sleep if it hasn' received any requests after certain amount of time or if it' been too active for the free tier the first time user accesses the site after it' been sleepingit will take longer to loadbut the server will respond to subsequent requests more quickly this is how heroku can afford to offer free deployments note securing the live project one glaring security issue exists in the way our project is currently deployedthe setting debug=true in settings pywhich provides debug messages when errors occur django' error pages give you vital debugging information when you're developing projectbut they give way too much information to attackers if you leave them enabled on live server we also need to make sure no one can get information or redirect requests by pretending to be the project' host let' modify settings py so we can see error messages locally but not on the live deploymentsettings py --snip-heroku settings if os getcwd(='/app'--snip-honor the ' -forwarded-protoheader for request is_secure(secure_proxy_ssl_header ('http_x_forwarded_proto''https' allow only heroku to host the project allowed_hosts ['learning-log herokuapp com' debug false static asset configuration --snip-
490
so the only server allowed to host the project is heroku you need to use the name of your appwhether it' the name heroku providedsuch as afternoon-meadow- herokuapp comor the name you chose at we set debug to falseso django won' share sensitive information when an error occurs committing and pushing changes now we need to commit the changes made to settings py to the git repositoryand then push the changes to heroku here' terminal session showing this processu (ll_env)learning_loggit commit -am "set debug=false for heroku [master set debug=false for heroku file changed insertions(+) deletions(- (ll_env)learning_loggit status on branch master nothing to commitworking directory clean (ll_env)learning_logwe issue the git commit command with short but descriptive commit message remember that the -am flag makes sure git commits all the files that have changed and records the log message git recognizes that one file has changed and commits this change to the repository at the status shows that we're working on the master branch of the repository and that there are now no new changes to commit it' essential that you check the status for this message before pushing to heroku if you don' see this messagesome changes haven' been committedand those changes won' be pushed to the server you can try issuing the commit command againbut if you're not sure how to resolve the issueread through appendix to better understand how to work with git now let' push the updated repository to heroku(ll_env)learning_loggit push heroku master --snip-remotepython app detected remoteinstalling dependencies with pip --snip-remotelaunching donev remoteremoteverifying deploy done to ef master -master (ll_env)learning_logheroku recognizes that the repository has been updatedand it rebuilds the project to make sure all the changes have been taken into account it doesn' rebuild the databaseso we won' have to run migrate for this update styling and deploying an app
491
your project with an extension we haven' defined for exampletry to visit page on your live deployment that doesn' give away any specific information about the project if you try the same request on the local version of learning log at django error page the result is perfectyou'll see informative error messages when you're developing the project furtherbut users won' see critical information about the project' code creating custom error pages in we configured learning log to return error if the user requests topic or entry that doesn' belong to them you've probably seen some server errors (internal errorsby this point as well error usually means your django code is correctbut the object being requested doesn' exista error usually means there' an error in the code you've writtensuch as an error in function in views py currentlydjango returns the same generic error page in both situationsbut we can write our own and error page templates that match the overall appearance of learning log these templates must go in the root template directory making custom templates in the learning_log/learning_log foldermake new folder called templates then make new file called html using the following code html {extends "learning_logs/base html%{block header %the item you requested is not available ( {endblock header %this simple template provides the generic error page information but is styled to match the rest of the site make another file called html using the following code html {extends "learning_logs/base html%{block header %there has been an internal error ( {endblock header %these new files require slight change to settings py settings py --snip-templates 'backend''django template backends django djangotemplates''dirs'[os path join(base_dir'learning_log/templates')]
492
--snip-}--snip-this change tells django to look in the root template directory for the error page templates viewing the error pages locally if you want to see what the error pages look like on your system before pushing them to herokuyou'll first need to set debug=false on your local settings to suppress the default django debug pages to do somake the following changes to settings py (make sure you're working in the part of settings py that applies to the local environmentnot the part that applies to heroku)settings py --snip-security warningdon' run with debug turned on in productiondebug false allowed_hosts ['localhost'--snip-you must have at least one host specified in allowed_hosts when debug is set to false now request topic or entry that doesn' belong to you to see the error pageand request url that doesn' exist (such as localhost: /letmein/to see the error page when you're finished checking the error pagesset debug back to true to further develop learning log (make sure debug is still set to false in the section of settings py that applies to the heroku deployment note the error page won' show any information about the user who' logged inbecause django doesn' send any context information in the response when there' server error pushing the changes to heroku now we need to commit the template changes and push them live to herokuu (ll_env)learning_loggit add (ll_env)learning_loggit commit -am "added custom and error pages files changed insertions(+) deletions(-create mode learning_log/templates/ html create mode learning_log/templates/ html (ll_env)learning_loggit push heroku master --snip-remoteverifying deploy done styling and deploying an app
493
ca master -master (ll_env)learning_logwe issue the git add command at because we created some new files in the projectso we need to tell git to start tracking these files then we commit the changes and push the updated project to heroku now when an error page appearsit should have the same styling as the rest of the sitemaking for smoother user experience when errors arise using the get_object_or_ (method at this pointif user manually requests topic or entry that doesn' existthey'll get server error django tries to render the page but it doesn' have enough information to do soand the result is error this situation is more accurately handled as errorand we can implement this behavior with the django shortcut function get_object_or_ (this function tries to get the requested object from the databasebut if that object doesn' existit raises exception we'll import this function into views py and use it in place of get()views py --snip-from django shortcuts import renderget_object_or_ from django http import httpresponseredirecthttp --snip-@login_required def topic(requesttopic_id)"""show single topic and all its entries ""topic get_object_or_ (topicid=topic_idmake sure the topic belongs to the current user --snip-now when you request topic that doesn' exist (for examplelocalhost: /topics/ /)you'll see error page to deploy this changemake new commitand then push the project to heroku ongoing development you might want to further develop learning log after your initial push to live server or develop your own projects to deploy there' fairly consistent process for updating projects firstyou'll make any changes needed to your local project if your changes result in any new filesadd those files to the git repository using the command git add (be sure to include the dot at the end of the commandany change that requires database migration will need this commandbecause each migration generates new migration file then commit the changes to your repository using git commit -am "commit messagethereafterpush your changes to heroku using the command git push heroku master if you migrated your database locallyyou'll need to migrate the live database as well you can either use the one-off
494
session with heroku run bash and run the command python manage py migrate then visit your live projectand make sure the changes you expect to see have taken effect it' easy to make mistakes during this processso don' be surprised when something goes wrong if the code doesn' workreview what you've done and try to spot the mistake if you can' find the mistake or you can' figure out how to undo the mistakerefer to the suggestions for getting help in appendix don' be shy about asking for helpeveryone else learned to build projects by asking the same questions you're likely to askso someone will be happy to help you solving each problem that arises helps you steadily develop your skills until you're building meaningfulreliable projects and you're answering other people' questions as well the secret_key setting django uses the value of the secret_key setting in settings py to implement number of security protocols in this projectwe've committed our settings file to the repository with the secret_key setting included this is fine for practice projectbut the secret_key setting should be handled more carefully for production site if you build project that' getting meaningful usemake sure you research how to handle your secret_key setting more securely deleting project on heroku it' great practice to run through the deployment process number of times with the same project or with series of small projects to get the hang of deployment but you'll need to know how to delete project that' been deployed heroku might also limit the number of projects you can host for freeand you don' want to clutter your account with practice projects log in to the heroku website (redirected to page showing list of your projects click the project you want to deleteand you'll see new page with information about the project click the settings linkand scroll down until you see link to delete the project this action can' be reversedso heroku will ask you to confirm the request for deletion by manually entering the project' name if you prefer working from terminalyou can also delete project by issuing the destroy command(ll_env)learning_logheroku apps:destroy --app appname here appname is the name of your projectwhich is either something like afternoon-meadow- or learning-log if you've renamed the project you'll be prompted to reenter the project name to confirm the deletion note deleting project on heroku does nothing to your local version of the project if no one has used your deployed project and you're just practicing the deployment processit' perfectly reasonable to delete your project on heroku and redeploy it styling and deploying an app
495
- live blogdeploy the blog project you've been working on to heroku make sure you set debug to false and change the allowed_hosts settingso your deployment is reasonably secure - more sthe get_object_or_ (function should also be used in the new_entry(and edit_entry(views make this changetest it by entering url like error - extended learning logadd one feature to learning logand push the change to your live deployment try simple changesuch as writing more about the project on the home page then try adding more advanced featuresuch as giving users the option of making topic public this would require an attribute called public as part of the topic model (this should be set to false by defaultand form element on the new_topic page that allows the user to change topic from private to public you' then need to migrate the project and revise views py so any topic that' public is visible to unauthenticated users as well remember to migrate the live database after you've pushed your changes to heroku summary in this you learned to give your projects simple but professional appearance using the bootstrap library and the django-bootstrap app using bootstrap means the styles you choose will work consistently on almost any device people use to access your project you learned about bootstrap' templatesand we used the static top navbar template to create simple look and feel for learning log you learned how to use jumbotron to make home page' message stand outand you learned to style all the pages in site consistently in the final part of the projectyou learned how to deploy project to heroku' servers so anyone can access it you made heroku account and installed some tools that help manage the deployment process you used git to commit the working project to repository and then pushed the repository to heroku' servers finallyyou learned to secure your app by setting debug=false on the live server now that you've finished learning logyou can start building your own projects start simpleand make sure the project works before adding complexity enjoy your learningand good luck with your projects
496
congratulationsyou've learned the basics of python and applied your knowledge to meaningful projects you've made gamevisualized some dataand made web application from hereyou can go in number of different directions to continue developing your programming skills firstyou should continue to work on meaningful projects that interest you programming is more appealing when you're solving relevant and significant problemsand you now have the skills to engage in variety of projects you could invent your own game or write your own version of classic arcade game you might want to explore some data that' important to you and make visualizations that show interesting patterns and connections you could create your own web application or try to emulate one of your favorite apps
497
if you write gamelet other people play it if you make visualizationshow it to others and see if it makes sense to them if you make web appdeploy it online and invite others to try it out listen to your users and try to incorporate their feedback into your projectsyou'll become better programmer if you do when you work on your own projectsyou'll run into problems that are challengingor even impossibleto solve on your own keep finding ways to ask for helpand find your own place in the python community join local python user group or explore some online python communities consider attending pycon near you as well you should strive to maintain balance between working on projects that interest you and developing your python skills in general many python learning sources are available onlineand large number of python books target intermediate programmers many of these resources will be accessible to you now that you know the basics and how to apply your skills working through python tutorials and books will build directly on what you learned here and deepen your understanding of programming in general and python in particular then when you go back to working on projects after focusing on learning about pythonyou'll be capable of solving wider variety of problems more efficiently congratulations on how far you've comeand good luck with your continued learning afterword
498
ins ta lling py thon python has several different versions and number of ways it can be set up on each operating system this appendix is useful if the approach in didn' workor if you want to install different version of python than the one that came with your system python on linux python is included by default on almost every linux systembut you might want to use different version than the default if sofirst find out which version of python you already have installed
499
open terminal window and issue the following commandpython --version python the result shows that the default version is howeveryou might also have version of python installed to checkenter the following commandpython --version python python is also installed it' worth running both commands before you attempt to install new version installing python on linux if you don' have python or if you want to install newer version of python you can install it in just few lines we'll use package called deadsnakeswhich makes it easy to install multiple versions of pythonsudo add-apt-repository ppa:fkrull/deadsnakes sudo apt-get update sudo apt-get install python these commands will install python to your system the following code will start terminal session running python python you'll also want to use this command when you configure your text editor to use python and when you run programs from the terminal python on os python is already installed on most os systemsbut you might want to use different version than the default if sofirst find out which version of python you already have installed finding the installed version open terminal windowand enter the following commandpython --version python appendix