Exercises for Real Python Part 2: Web Development with Python by Michael Herman. Share with the world!
realpython / book2-exercises Goto Github PK
View Code? Open in Web Editor NEWBook 2 -- Exercises for the book
Book 2 -- Exercises for the book
Exercises for Real Python Part 2: Web Development with Python by Michael Herman. Share with the world!
Typo on very last line:
"
I have edited the controller likewise the book said-
new_task = Task(
form.name.data,
form.due_date.data,
form.priority.data,
datetime.datetime.utcnow(),
'1',
'1' )
But while i ran the app, there occurred an error which points out that i was assigning an integer type to posted_date which should be a date type. So i have reconfigured the code like this-
new_task = Task(
form.name.data,
form.due_date.data,
form.priority.data,
'1',
datetime.datetime.utcnow(),
'1'
)
And now it works.
Hey everyone, does anyone else get an error while trying to log_in with a previous registered account?
AttributeError at /sign_in
'User' object has no attribute 'check_password'
traceback
Request Method: POST
Request URL: http://127.0.0.1:8000/sign_in
Django Version: 1.6.5
Exception Type: AttributeError
Exception Value:
'User' object has no attribute 'check_password'
Exception Location: /home/mat/Desktop/django-projects/book2-exercises/django_mvp/mvp/payments/views.py in sign_in, line 24
Python Version: 2.7.5
looks like its comming from the payments/views.py
if results[0].check_password(form.cleaned_data['password']):
def sign_in(request):
user = None
if request.method == 'POST':
form = SigninForm(request.POST)
if form.is_valid():
results = User.objects.filter(email=form.cleaned_data['email'])
if len(results) == 1:
if results[0].check_password(form.cleaned_data['password']):
request.session['user'] = results[0].pk
return HttpResponseRedirect('/')
else:
form.addError('Incorrect email address or password')
else:
form.addError('Incorrect email address or password')
else:
form = SigninForm()
print form.non_field_errors()
return render_to_response(
'sign_in.html',
{
'form': form,
'user': user
},
context_instance=RequestContext(request)
)
Thanks for any headsup!
Typo in Paragraph before bullet #4, "So in the better_hello() function", should be "So in the better() function".
In the book, we are adding a step for checking the feature of "a user can add post after login". The code is like this-
@when(u'we add a new entry with "{title}" and "{text}" as the title and text')
def add(context, title, text):
context.page = context.client.post(
'/add',
data = dict(username=title, password=text),
follow_redirects=True)
assert context.page
The data variable should be assigned with the dict like this-
data = dict(title=title, text=text)
The code is ok in the course repository.
At chapter 10, Page 159-160 of the Real Python Part-2 book, we are defining RegisterForm() class for allowing the new user to register.
There, we are adding 'confirming password' feature like this-
confirm = PasswordField(
'Repeat Password',
[DataRequired(), EqualTo('password', message='Passwords must match')]
)
I think the terms within third braces should be assigned to 'validators' like this-
confirm = PasswordField(
'Repeat Password',
validators = [DataRequired(), EqualTo('password', message='Passwords must match')]
)
If my assumption is wrong, what is the reason for not adding it?
Thanks in advance.
I have been trying to crawl on hackernews according to the code provided. I have faced some problem. I have reconstructed the code in spider.py like this-
From
from scrapy.spider import BaseSpider
...............
class MySpider(BaseSpider):
.........
To
from scrapy.spiders import Spider
..................
class MySpider(Spider):
and than it has worked. Is this a problem? Should i make a pull request?
Another question about the output of the crawler- Here is the output:
2015-09-15 19:30:04 [scrapy] INFO: Scrapy 1.0.3 started (bot: hackernews)
2015-09-15 19:30:04 [scrapy] INFO: Optional features available: ssl, http11
2015-09-15 19:30:04 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE':'hackernews.spiders', 'SPIDER_MODULES': ['hackernews.spiders'],'BOT_NAME': 'hackernews'}
2015-09-15 19:30:04 [scrapy] INFO: Enabled extensions: CloseSpider, TelnetConsole, LogStats, CoreStats, SpiderState
2015-09-15 19:30:04 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware,ChunkedTransferMiddleware, DownloaderStats
2015-09-15 19:30:04 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2015-09-15 19:30:04 [scrapy] INFO: Enabled item pipelines:
2015-09-15 19:30:04 [scrapy] INFO: Spider opened
2015-09-15 19:30:04 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2015-09-15 19:30:04 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2015-09-15 19:30:04 [scrapy] INFO: Closing spider (finished)
2015-09-15 19:30:04 [scrapy] INFO: Dumping Scrapy stats:
{'finish_reason': 'finished','finish_time': datetime.datetime(2015, 9, 15, 13, 30, 4, 895000), 'log_count/DEBUG': 1,'log_count/INFO': 7,'start_time': datetime.datetime(2015, 9, 15, 13, 30, 4, 886000)}
2015-09-15 19:30:04 [scrapy] INFO: Spider closed (finished)
Is the output ok? I can't understand the meaning of the output. Shouldn't we see some title and text?
Page 586 - "and create uility methods."
When I attempted the last exercise starting on Page 511 (Templates), my betterhello.html for the better
function would not render in my browser, and I kept receiving a "TemplateDoesNotExist at ..." error. I could not figure out where I was going wrong until I went to the RealPython_Book2_Exercises directory that I had, navigated to your project, and started the server to find that the page worked in your project! I then started copying and pasting the 6 or so files of code one by one until the betterhello.html file rendered at localhost:8000/better/. I had the exact same code EXCEPT in the settings.py file (under the "hello_world_project" directory) where there was a TEMPLATES = [....] list in my file where there was not one in yours (starting at line 64 or so). When I deleted this entire list, my betterhello.html file rendered at localhost:8000/better/ . The TEMPLATES list python code looks like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Looks like they updated some functionality after the book was written. (I also had the same Django Version 1.8.2).
NON - ISSUE - I guess I still haven't mastered the art of proper indentation.
The test.py script, as shown on this page, doesn't work, and the test_user_setup function doesn't exist in the book2-exercises master to compare.
Ninja edit: I'm seeing the same problem for the test.py that begins on page 191.
As a test, I copied the complete test.py script from flasktaskr-03 in the master, and it executed and ran the tests properly.
Hello, i am in at Chapter 13, page 215. It says my static folder should be look like this-
static
css
bootstrap.min.css
js
jquery-1.11.1.min.js
bootstrap.min.js
styles.css
I have downloaded Bootstrap files from this link- bootstrap_download. But i couldn't find any jquery-1.11.1.min.js file in these.
In 15.1.1.2 Write Code section it says:
“Simply add the above code to the else block in the login() function. ”
It should be
“Simply add the above code to the if block in the login() function. ”
On page 585:
Admmin panel
Hello, at the page 303 of the book, the test of the response for the URL of invalid task_id is defined like this-
def test_invalid_resource_endpoint_returns_error(self):
self.add_tasks()
response = self.app.get('api/tasks/209', follow_redirects=True)
self.assertEquals(response.status_code, 200)
self.assertEquals(response.mimetype, 'application/json')
self.assertIn('Element does not exist', response.data)
There is a typo in the line-
self.assertEquals(response.status_code, 200)
The returned status code should be 404, according to the defined route of project/views.py.
On page 113 going into page 114, item #3 instructs us to "add pdb.set_trace() within the function to set your first breakpoint".
However, the code block that follows doesn't have it added, nor does it have the import pdb.
Page 586 - Please, use comma instead period.
One of the main features of MongoEngine. Despite the fact that Mongo does not require a schema
Should be:
One of the main features of MongoEngine, despite the fact that Mongo does not require a schema
Each of the four fields contains this if statement:
{% if form.name.errors %}
should be:
{% if form.email.errors %}
{% if form.password.errors %}
{% if form.confirm.errors %}
There is inconsistent naming of the tasks table. First, on page 151, when the table is created, you call
__tablename__ = "tasks"
Starting on page 155, you call that very same table ftasks
.
It's not really a problem, but it's still confusing.
on page 595:
Instead of:
Ad the Database layer:
Should be:
At the Database layer:
Instead of:
Thinka bout testing as well:
Should be:
Think about testing as well:
I think the tutorial's connect_db() function should be updated to
sqlite3.connect(app.config['DATABASE_PATH'])
This way, the Flask server can be run from any base directory, rather than only working from the project directory.
In my payments.views.register, my app crashes upon a post request because stripe_token is None. I understand it is using the hiddenInput widget, and therefore must get set from the server, but I do not see where this happens anywhere. For example if UserForm was a ModelForm, specifying a default value for stripe_token would fix this problem. How is this dealt with in your code?
In templates/cardform.html, line 26 defines a label that seems to never be used.
label for="expiry_date">Expiration date</label
Did you mean for line 26 to be this?
div class="input" id="expiry_date
Thank you!
Jonathan
Typo in 4th sentence from the top: "Before we look at example". Thank you!
When I try to execute
heroku addons:add heroku-postgresql:dev
I receive the following error:
WARNING: heroku addons:add
has been deprecated. Please use heroku addons:create
instead.
! That add-on plan is only available to select users.
I could still fire up my app, login, add, remove, and mark tasks as complete. I'm not sure how the Postgres db fits in, but mine still worked. Just wanted to make everyone aware!
Before the in line 40, there should be an opening
tag that corresponds to the closing tag on line 47.
Going through chapter 29. on page 586 you're asked to create an app. When doing so, I get this error:
"mongoengine.connection.ConnectionError: Cannot connect to database default: False is not a read preference."
I used django 1.8.2 and pymongo 3.0.2.
Was able to fix it by using pymongo 2.8.
AOL stock data isn't showing up (shows up as N/A). I don't think it's publicly traded anymore!
Near the bottom of page 277, I believe there is a typo when discussing where the errorhandler code should be located:
"Update project/views.py:"
I think it should be:
"Update project/init.py:"
Thank you!
End of paragraph under Create a Pull Request header, the word "Master brunch" is used. I think it should be "branch"? Thanks!
This is the wrong code:
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"></script>{% block extrahead %}
{% endblock %}
</script>
Here is how it should be:
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"> {% block extrahead %} {% endblock %} </script>Hello, I am not able to understand the process of defining 'task_id' like this-
task_id = IntegerField('Priority')
My question is why we are using 'Priority' within IntegerField().
I have my own explanation that we are going to use that in 'priority' so that we can prioritize tasks using the task_id. But i am not sure here.
I couldn't find any 'help tag' here or else it would been 'help' issue. I am following your Real Python books part 2 now. I couldn't find any forums for such kind of questions either.
Not sure why people are referring to page #'s...the page #'s change depending on your viewer, right?
Anyway...
14.3.2
3 says:
“Add “static” and “templates” directories within both the “tasks” and “users” directories.”
But right after that you list how the directory structure should look, and those folders aren't in tasks and users. Nor are they in the git solution.
Step 4 does not make a lot of sense, either. I'm guessing that steps 3 and 4 should be removed.
if x in set(["1", "2", "3", "4"]):
Can be simplified to:
if x in {"1", "2", "3", "4"}:
Obviously, the result is the same for both, but you can avoid the function call with the latter.
Line 19 in the code block:
youtube_service.GetYouTubePlaylistVideoFeed(playlist_url)
returns a "No Longer Available" error (410). I have crawled over Google and can't find why I am being returned this error. I am curious to see if anyone else can replicate it. I tried hermanmu and my own youtube user id and I couldn't get it to work. Thanks!
Hello, in the book, the 404 error handling process is defined like this-
@app.errorhandler(404)
def internal_error(error):
return render_template('404.html'), 404
Is it necessary to write a 404 after render_template('404.html')? The function has worked without it-
@app.errorhandler(404)
def internal_error(error):
return render_template('404.html')
It is at 281 page of the book.
I was working through book two in the Travis CI Setup section, and I got to the point where I am supposed to installed RVM. I would recommend adding two steps in the OSX/Linux section
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
. I couldn't install RVM without it!rvm install 1.9.3
command. I read you could also use bash -l
.Thanks again for the great book! I am learning a ton!
I am at chapter 11 and i have applied error handling parts. But i am having problem while adding new tasks. The error is showing that
'function' object is not iterable
We are looping over the function in tasks.html while adding task-
{% for task in open_tasks %}
<tr>
<td width="200px">{{ task.name }}</td>
...................
<td>
<a href="{{ url_for('delete_entry', task_id = task.task_id) }}">Delete</a>
<a href="{{ url_for('complete', task_id = task.task_id) }}">Mark as Complete</a>
</td>
</tr>
{% endfor %}
The operation for closing tasks are functioning alright though.
I have googled but couldn't able to find any solution. Plus, as far as i know in python 'function' object is not iterable.
The problem wouldn't exist (may be) if we declare open_tasks and closed_tasks as a variable (like previous chapters) within task() function in views.py instead of defining two functions (open_tasks() and closed_tasks()) for the purpose.
Typo in first sentence of first paragraph under Paragraph Header Google Directions API, "between to points" should be "two". Thanks! I'm loving these books!
trying to add the 'add' route and function at the end of the 'blog.py' file results with error. Text should mention the right place, and the reason for it. (For me it worked when I placed the 'add's after the 'login' route and before the 'main' one).
Please review pages 613 and 614.
Figure 30.2: Django Flat Pages App - adding a new page. This is along the HTML code, and it's confusing the reader.
In book 2, page 513.
The about function in the view returns some text and a link, but the link (anchor tag) is not closed properly.
Missing > at the end
book 2 page 557. The code showing the added Bootstrap Grid System is missing a closing div. the
In book 2 page 609 it says
"the relationship is the same for Django templates as it is for Jinga templates
in Flask." Shouldn't it be Jinja, not jinga?
#EDIT 3 #
In book 3 page 12 the last line says:
"you have any suggestions or feedback, please contact is."
it should probably be us, not is.
Last chapter in book 2.
I probably need to go through the chapter again to determine if the error was on my end (which I suspect it is), but I got an error when i tried to create an account because the table didn't exist (payments_user, i think) and had to run syncdb again.
#EDIT 5 #
Page 590
line 21 contain "</script>" but there's no open script tag for it to close. Commenting that line out fixed the code.
In chapter 21, you guys use stripe to process user payments. This is done by replacing the default django user model for an custom user model, is this the best practice?
Even on the django documentation they kind of advise against it (look at the warning): https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#substituting-a-custom-user-model
I think the best practice would be to extend the user model with the necessary information your user needs and let the default user model handle the default fields like username, firstname, is_staff, email etc., am i wrong?
https://www.reddit.com/r/learnpython/comments/3uesqy/django_auth_question/
^This is the error I am getting. (InvalidRequestError: No such token:None)
What OP did to solve his problem is that he supplied the credit card information in the views which im sure is not the right way.
Why am i getting this error
Trying to update the controller default.py
with a function for the note(s) page... my code looks (as far as I can tell) the same as shown here in the repo, line 26 but I am getting an error ticket when I try to actually access the page:
File "/home/memilanuk/web2py/applications/py2manager/controllers/default.py", line 57, in note
form = crud.create(db.note) if auth.user else "Login to Post to the Project"
NameError: global name 'crud' is not defined
Not sure if its a version thing; I'm using web2py 2.12.3 on pythonanywhere.com, vs. 2.8.2 as used in the book. Web2py is supposed to be pretty good about backwards compatibility, and I thought crud
was a standard feature...?
Not sure if I've missed something, but the chapter says to download Scrapy==0.16.4 and then later on, on page 474 to use the function sel ( sel.xpath('//td[@Class="title"]') ).
When using the function sel, this error is returned ->
NameError: name 'sel' is not defined.
according to this guy, sel wasn't added until version 0.20.
http://stackoverflow.com/questions/22115982/scrapy-shell-did-not-recognize-sel-object
Hello,
I'm struggling whit a 404 error after I login whit admin, admin into mine flasktaskr application.
It is not redirecting me to tasks.html and I am unable to see the template. I'm trying to google an answer but I'm very confused about this.
Have tried everything but it still give me 404 after I login.
This is the output http://127.0.0.1:5000/post?username=user&password=pass, how to debug this?
This is mine repository for the application https://github.com/Copser/AddFlaskTaskr.
On page 116 going into page 117, item #9 instructs us to "Refactor".
However, the code block that follows, even when copied and pasted, doesn't function properly. After a bit of debugging, I found that answer was bound to a string, so in the elif, we're trying to compare a string to an int resulting in a failure every time.
It is possible that this was intentional to get us to continue debugging and practicing to get it working; however, I very nearly moved on, since that fact was clearly stated.
PS - it is entirely possible that I did something else wrong and this entire issue is moot. :)
Last line in the NOTE paragraph: "se fit" should be "see fit". Thanks! I'm loving this book!
The second socrata project only loops through one page, and I can't find any errors in my code (comparing it to the files provided). Where exactly should the "for looping" be occuring, or is the rule what sets the "for loop"? Thanks!
Typo in the first line "posts.html" should be "post.html". Thanks!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.