coreymschafer / code_snippets Goto Github PK
View Code? Open in Web Editor NEWLicense: MIT License
License: MIT License
Greetings, Corey! Colud you please help a newbie find an answer? Something has changed in BS, so that:
yt_link = f'https://youtube.com/watch?v={vid_id}'
^
SyntaxError: invalid syntax
i do register, and click sign up then
Request Method: | POST |
---|---|
http://127.0.0.1:8000/register/ | |
2.2 | |
TypeError | |
save() got an unexpected keyword argument 'force_insert' | |
C:\Users\62857\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py in create, line 422 | |
C:\Users\62857\AppData\Local\Programs\Python\Python37-32\python.exe | |
3.7.3 | |
['D:\Projek Ricko\Django\django_projek', 'C:\Users\62857\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\62857\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\62857\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\62857\AppData\Local\Programs\Python\Python37-32', 'C:\Users\62857\AppData\Local\Programs\Python\Python37-32\lib\site-packages'] | |
Sat, 13 Apr 2019 00:03:43 +0000 |
the input is successful but does not go to the login form
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/auth/user/
Django Version: 2.2.1
Python Version: 3.6.7
Installed Applications:
['blog.apps.BlogConfig',
'users.apps.UsersConfig',
'crispy_forms',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/aytekin/.local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/home/aytekin/.local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/home/aytekin/.local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/aytekin/.local/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper
606. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/aytekin/.local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "/home/aytekin/.local/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "/home/aytekin/.local/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner
223. return view(request, *args, **kwargs)
File "/home/aytekin/.local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "/home/aytekin/.local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "/home/aytekin/.local/lib/python3.6/site-packages/django/contrib/admin/options.py" in changelist_view
1698. response = self.response_action(request, queryset=cl.get_queryset(request))
File "/home/aytekin/.local/lib/python3.6/site-packages/django/contrib/admin/options.py" in response_action
1397. response = func(self, request, queryset)
File "/home/aytekin/.local/lib/python3.6/site-packages/django/contrib/admin/actions.py" in delete_selected
28. deletable_objects, model_count, perms_needed, protected = modeladmin.get_deleted_objects(queryset, request)
File "/home/aytekin/.local/lib/python3.6/site-packages/django/contrib/admin/options.py" in get_deleted_objects
1820. return get_deleted_objects(objs, request, self.admin_site)
File "/home/aytekin/.local/lib/python3.6/site-packages/django/contrib/admin/utils.py" in get_deleted_objects
118. collector.collect(objs)
File "/home/aytekin/.local/lib/python3.6/site-packages/django/contrib/admin/utils.py" in collect
181. return super().collect(objs, source_attr=source_attr, **kwargs)
File "/home/aytekin/.local/lib/python3.6/site-packages/django/db/models/deletion.py" in collect
224. field.remote_field.on_delete(self, field, sub_objs, self.using)
Exception Type: TypeError at /admin/auth/user/
Exception Value: 'str' object is not callable
Hello!
In your Django code snippets for "06-User-Registration-Form", I'm getting this error when I try to create new user with existing username.
ValueError: The view user_auth.views.register didn't return an HttpResponse object. It returned None instead.
This is my forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2',)
This is my views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from user_auth.forms import UserRegisterForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect('index')
else:
form = UserRegisterForm()
return render(request, 'register.html', {'form':form})
Can you please help me to figure out this problem?
Thanks in advance.
Not an issue but a question -- When I attempt to use models in forms, I get the error "No application found. Either work inside a view function or push" when running the application. Is there a way to use and query models within forms?
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField
from wtforms.validators import DataRequired
from flaskblog.models import Post
def posttest():
return Post.query.first().content
class PostForm(FlaskForm):
title = StringField("Title", validators=[DataRequired()])
content = TextAreaField("Content", validators=[DataRequired()], default=posttest())
submit = SubmitField("Post")
Ive been getting RelatedObjectDoesNotExist at /profile/
User has no profile. even though my code is the same exact as your.
Corey,
thanks for your imazing playlist at youtube, but this is something i did not quite understood ! why var update (first) did not pass to the email!
it does passed to full name function! but it does not to email!!
Hello,
since the blueprint and configuration chapter i have this error when i launch the unicorn command
gunicorn flaskblog
[2018-05-09 15:47:16 +0200] [20254] [INFO] Starting gunicorn 19.8.1
[2018-05-09 15:47:16 +0200] [20254] [INFO] Listening at: http://127.0.0.1:8000 (20254)
[2018-05-09 15:47:16 +0200] [20254] [INFO] Using worker: sync
[2018-05-09 15:47:16 +0200] [20257] [INFO] Booting worker with pid: 20257
[2018-05-09 15:47:16 +0200] [20257] [ERROR] Exception in worker process
Traceback (most recent call last):
File "/home/vince/VooxelFlaskEnv/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
worker.init_process()
File "/home/vince/VooxelFlaskEnv/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
self.load_wsgi()
File "/home/vince/VooxelFlaskEnv/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
self.wsgi = self.app.wsgi()
File "/home/vince/VooxelFlaskEnv/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
File "/home/vince/VooxelFlaskEnv/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
return self.load_wsgiapp()
File "/home/vince/VooxelFlaskEnv/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
return util.import_app(self.app_uri)
File "/home/vince/VooxelFlaskEnv/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
import(module)
ModuleNotFoundError: No module named 'flaskblog'
[2018-05-09 15:47:16 +0200] [20257] [INFO] Worker exiting (pid: 20257)
[2018-05-09 15:47:16 +0200] [20254] [INFO] Shutting down: Master
[2018-05-09 15:47:16 +0200] [20254] [INFO] Reason: Worker failed to boot.
I do not understand what to do with this.
Did anyone have the same issue?
Thank you for your great Flask Tutorial.
Hi,
Thanks for the code and youtube tutorial. They are awesome.
I notice that the code of the video is different from the github one.
For instance the class methods are not there.
Would it be possible to share it?
Thanks again,
Marco
Add an appropriate license for authorized copy, reproduction of the source code and re-distribution?
Hey,
I am currently working on your tutorial titled: "Python Django Tutorial: Full-Featured Web App Part 12 - Email and Password Reset"
I downloaded the code_snippets for Part 12 and I can't seem to receive any emails for password reset.
What have i tried:
I have already set "Allow less secure apps: ON" in my google account. I tried looking everywhere on Google and the answers provided are mostly asking me to try to Allow less secure apps on Google. It's been 24H I can't seem to find what have I done wrong..
I also tried using the EmailMessage class at my views.py. I am able to send email to myself. I don't think there is any issue with the authentication of my email.
I wants to add a option of changing the language in django WebApp. How I can did it?
My django WebApp link - https://github.com/smahesh29/Django-WebApp
Suggest me the changes into the code. If any tutorial on it please give the link.
I have an error with urls.py
AttributeError: module 'homepage.views' has no attribute 'home'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home(), name='homepage-home'),
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
def home(request):
return HttpResponse('
TemplateSyntaxError at /
Could not parse the remainder: '|' from '|'
error at line 24:
{% if page_obj.number == num %}
error.txt
In part 3 flaskblog.py I'm getting an error stating, "No module named 'forms.'" I resorted to copy/paste the code from here but still getting the error. I'm stumped. I copy/pasted the flaskblog.py, register.html, and login.html code, but to no avail.
What am I getting wrong?
Thanks
Thanks for bringing such great tutorial, I am really interested in how to change the Profile update function to classed based view.
I did some research, the things covered are mostly based on one form, not combo of two forms, does anyone know how to solve it? thanks
def profile(request):
if request.method == "POST":
u_form = UserUpdateForm(request.POST,instance=request.user)
p_form = ProfileUpdateForm(request.POST,request.FILES,instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request,"Your accunt has been updated, you are now be able to log in !")
return redirect('profile')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form':u_form,
'p_form':p_form
}
return render(request,'users/profile.html',context)
I tried with updateview, detailview, but all fails
thanks
I am using Python 2.7, the registration form didn't get the flash message
ERROR: Could not find a version that satisfies the requirement flash (from versions: none)
ERROR: No matching distribution found for flash
I took a look at the final deployed django website on heroku to see how the images were displayed in the HTML. I saw that the src parameter of the img tags look something like
<img class="rounded-circle article-img" src="https://django-blog-bucket-experiement.s3.amazonaws.com/profile_pics/logo.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAI5JMO5BA2FV5LMWA%2F20190816%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20190816T212801Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=4319df2a3691fd7641725df9efc918a7458afe7d55370f1c06cb0fd6bd0252b6">
This displays both the
On AWS it says that it is important to not give out the Access Key ID.
Is this a security issue? If so, how can it be changed?
Am attempting to follow along, however I did skip videos 6-11? on the django series. I feel kind of foolish, however I am experiencing this 500 error on the homepage, however, the other pages work as expected. (This is a live version on heroku, but I have my site disabled, as I need to actually add content, and get the homepage to work first :D)
Performing system checks...
System check identified no issues (0 silenced).
February 25, 2019 - 23:27:30
Django version 2.1.7, using settings 'django_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[25/Feb/2019 23:27:33] "GET / HTTP/1.1" 500 27
[25/Feb/2019 23:27:37] "GET /admin/ HTTP/1.1" 302 0
[25/Feb/2019 23:27:37] "GET /admin/login/?next=/admin/ HTTP/1.1" 500 27
[25/Feb/2019 23:27:42] "GET /login HTTP/1.1" 301 0
[25/Feb/2019 23:27:42] "GET /login/ HTTP/1.1" 500 27
[25/Feb/2019 23:27:49] "GET /about/ HTTP/1.1" 500 27
Thank you in advance!
Cody Quist
I do not have a sign up for https://images.unsplash.com. So I change the url to github and wound up with one file.
from:
def download_image(img_url):
img_bytes = requests.get(img_url).content
img_name = img_url.split('/')[3] #<-------------------
img_name = f'{img_name}.jpg' #<-------------------
with open(img_name, 'wb') as img_file:
img_file.write(img_bytes)
print(f'{img_name} was downloaded...')
To:
def download_image(img_url):
img_bytes = requests.get(img_url).content
img_name = img_url.split('/')[-1] #<------------------
#img_name = f'{img_name}.jpg' #<------------------
with open(img_name, 'wb') as img_file:
img_file.write(img_bytes)
print(f'{img_name} was downloaded...')
@CoreyMSchafer Kinddly help me to solve this issue i am not finding where is the issue. I am learning Flask_Blog tutorial
Thank you
suggested enhancement:
function conda_auto_env() {
if [ -e "environment.yaml" ]; then
ENV_NAME=$(head -n 1 environment.yaml | cut -f2 -d ' ')
# Check if you are already in the environment
if [[ $CONDA_PREFIX != *$ENV_NAME* ]]; then
# Try to activate environment
source activate $ENV_NAME &>/dev/null
fi
else
source deactivate
fi
}
Hi,
I was try to use package structure in the project with small changes here and there. When i do python run.py I get the following errors.
only folder names are different and some code. I tried to look out the answers in stack overflow but could not understand a thing as i am noobie.
> /home/#####/anaconda2/envs/py3/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py:794: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
> 'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
> Traceback (most recent call last):
> File "run.py", line 3, in <module>
> from vf import app
> File "/home/####/Documents/versatile/vf/__init__.py", line 12, in <module>
> class User(db.model):
> AttributeError: 'SQLAlchemy' object has no attribute 'model'
Please kindly help me out?
Hi, (if using python 2.7, solved in py 3) you might encounter a encode error when trying to write the csv file.
"UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 28: ordinal not in range(128)"
Might be bs4's autodecoding not kicking in correctly.
Solution
.encode('utf8')
Workaround
.encode('ascii', 'ignore')
Dirty Workaround
headline = headline.replace(u"\u2018", "'").replace(u"\u2019", "'").replace(u"\u2013","-").replace(u"\u2026","...")
summary = summary.replace(u"\u2018", "'").replace(u"\u2019", "'").replace(u"\u2013","-").replace(u"\u2026","...")
yt_link = yt_link.replace(u"\u2018", "'").replace(u"\u2019", "'").replace(u"\u2013","-").replace(u"\u2026","...")
Ref on python 2.7 unicode
Hi @CoreyMSchafer is there a requirements.txt
file that you can add to the flask_blog
project? To help setup a venv with all the right packages installed from the get-go...
Hi Corey,
Your tutorial is excellent, helped me a lot, thank you so much.
I followed your steps in tutorial 2 for Flask Blog, when I used bootstrap the webpage styling did not change, all the navigation bars are stuck together. I am not sure why?
By the way I am using python 2, does bootstrap require python 3?
Thank you,
Ling
Hi Corey, not sure if you're still reading these comments. Loving the tutorials. Am up to the end of the video (7) for changing the user's profile image. All works until this part.
Pillow is installed for PIP. Run the code and I get the following error.
website_1 | File "/logrr/logrr/blueprints/login/views.py", line 74, in accountPage
website_1 | picture_file = save_picture(form.picture.data)
website_1 | File "/logrr/logrr/blueprints/login/views.py", line 57, in save_picture
website_1 | i.save(picture_path)
website_1 | File "/usr/local/lib/python3.7/site-packages/PIL/Image.py", line 2004, in save
website_1 | fp = builtins.open(filename, "w+b")
website_1 | FileNotFoundError: [Errno 2] No such file or directory: '/logrr/static/images/profile_pics/757b0bf5ed6b98cb.jpg'
I check and sure enough, in the profile_pics folder there is no file. I changed permissions so that all users can access the folder with full access so it can't be that.
Line 74 is calling the save function:
picture_file = save_picture(form.picture.data)
Line 57 is the actual save line in the function:
i.save(picture_path)
What could be wrong? I'm a little stumped. Thank you
I can't access profile photos through the shell but I can see them in the admin portal. And also it gives the error: Instance of 'OneToOneField' has no 'username' member
at the moment in Part 8
code_snippets/Django_Blog/08-Profile-And-Images/django_project/
I am following your youtube python tutorials for Python/Flask_Blog/ and it is fascinating. Wondering if you are planning to put additional videos for unit testing.
Thank you!
Going through the Django blog project. I tried a few of the projects and all of the ones I tried (01, 03, 06, 12) and all of them fail when creating a super user from the command line using "python manage.py createsuperuser". It seems like the only time it works is just as you create the django project.
HI Corey,
Thanks for posting this django tutorial. I have finished the tutorial and am now working through making my own project with a similar structure and noticed a few issues that may or may not be relevant.
line 23 in base.html - should it be navbar-fixed-top instead of fixed-top. I don't think it will create issues for the tutorial but incase you want to add it for completeness.
Hi Schafer,
It seems the Yahoo Finances API is not working anymore, but I believe this link will work to you at least for your demo :
https://api.worldtradingdata.com/api/v1/stock?symbol=AAPL&output=json&api_token="YOUR API TOKEN"
You only need to create an account in https://www.worldtradingdata.com. But at least it is free! Or use any other API json file.
How to add links( like google.com) to a post (content). I tried doing it but failed
Took codebase from : https://github.com/CoreyMSchafer/code_snippets/tree/master/Decorators
I added below snippet at the end of decorator.py and it should have created log file named as check_kw.log
However, it didn't do it. It just appended the logs created by this function to display_info.log file.
Is there anything else need to change in my_logger?
@my_logger
@my_timer
def check_kw(*args, **kwargs):
time.sleep(1)
print('check_kw ran with arguments ({}, {})'.format(args, kwargs))
keywordargs = {"arg3": 3, "arg2": "two", "arg1": 5}
check_kw(**keywordargs)
code_snippets/Automation/rename.py
Line 43 in 2d2e572
$ flake8 . --count --show-source --statistics --select=E9,F63,F7,F82
./Closure/html_closure.py:7:16: F821 undefined name 'y'
return x + y
^
./Mutable/code.py:3:39: F821 undefined name 'a'
print('Address of a is: {}'.format(id(a)))
^
./Automation/rename.py:43:33: F821 undefined name 'file_num'
new_name = '{}-{}{}'.format(file_num, file_title, file_ext)
^
./Automation/rename.py:43:43: F821 undefined name 'file_title'
new_name = '{}-{}{}'.format(file_num, file_title, file_ext)
^
./Automation/rename.py:45:15: F821 undefined name 'fn'
os.rename(fn, new_name)
^
5 F821 undefined name 'file_num'
5
First off, thank you for doing these tutorials; it has really helped me with web development. However, I have had an issue in your Python Flask tutorials at tutorial #11. I always get the error:
AttributeError: 'Blueprint' object has no attribute 'json_encoder'
I am able to access the website, but it shows the above error.
The only solution I got was by removing the Secret_Key
in CONFIG class. But when I access my account, it throws another error saying that it needs the secret key. I have all my dependencies imported prior to your requirements.txt; I'm not sure what's wrong.
this also gives cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user [SQL: 'SELECT user.id AS user_id, user.username AS user_username, user.email AS user_email, user.image_file AS user_image_file, user.password AS user_password \nFROM user \nWHERE user.username = ?\n LIMIT ? OFFSET ?'] [parameters: ('harry potter', 1, 0)] (Background on this error at: http://sqlalche.me/e/e3q8)
hello my name is Amani , how can you connect flask app with existing database
I wrote the same exact issue, checked my environment settings, printed out everything, and they still give out the same OSError.
In file code_snippets/Django_Blog/02-Application-And-Routes/django_project/django_project/urls.py
, i found this:
path('', include('blog.urls')),
which should be replaced by path('blog/', include('blog.urls'))
as the code in videos.
Please check it.
I am just curious about the repo, no readme and no description. But so many stars.
Not sure why photos are not shown, but I have forked in my repo, I have created a new user and default photo should be shown, but still only getting empty image:
at the moment in Part 8
code_snippets/Django_Blog/08-Profile-And-Images/django_project/
I noticed there doesn't appear to be any tests in the Flask_Blogs project
Hi there.
I was reading the code of flask blog app and in logout route definition isn't login_required should be used? Like:
@app.route("/logout")
def logout():
logout_user()
return redirect(url_for('home'))
to
@app.route("/logout")
@login_required
def logout():
logout_user()
return redirect(url_for('home'))
Thanks for all your amazing tutorials.
obj.save(force_insert=True, using=self.db)
TypeError: save() got an unexpected keyword argument 'force_insert'
After adding additional argument to the class Profile(models.Model):
(django_project/users/models.py)
at line 13
def save(self, ** kwargs):
It starts working
all the https and www's have been removed already.
smtplib.SMTPSenderRefused
smtplib.SMTPSenderRefused: (530, b'5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError v2sm22720640pgr.2 - gsmtp', '[email protected]')
i just completed mr coreyMSchafer vedio tutorial Flask dev environment. but i get this error message.
on init.py already write the code :
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.