How to import a subfolder in the template directory while using blueprints and render_template and url_for - flask

I found this link but can't figure out how to use it for render_template and url_for when using blueprints.
How to import the template into a subdirectory of the templates folder in Flask?
Here is a picture of the templates folder and subfolder
Here is what I have tried.
I tried this below, userinfo is my blueprint
I assume this will work.
#userinfo.route('/donations')
def donations():
return render_template('stripe_payment/donations.html', products=products)
Here is the link to donations route. I assume this is causing the error. How do I fix this?
<h2> Click Here to donate </h2>
Here is the error
Traceback (most recent call last):
File "C:\Users\nmyle\anaconda3\envs\py\Lib\site-packages\flask\app.py", line 2091, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\nmyle\anaconda3\envs\py\Lib\site-packages\flask\app.py", line 2076, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\nmyle\anaconda3\envs\py\Lib\site-packages\flask\app.py", line 2073, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\nmyle\anaconda3\envs\py\Lib\site-packages\flask\app.py", line 1518, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\nmyle\anaconda3\envs\py\Lib\site-packages\flask\app.py", line 1516, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\nmyle\anaconda3\envs\py\Lib\site-packages\flask\app.py", line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:\Users\nmyle\OneDrive\Desktop\flaskcodeusethis\flaskblog2\app\userinfo\routes.py", line 77, in home
return render_template('home.html', posts=posts, title='home')
File "C:\Users\nmyle\anaconda3\envs\py\Lib\site-packages\flask\templating.py", line 147, in render_template
return _render(
File "C:\Users\nmyle\anaconda3\envs\py\Lib\site-packages\flask\templating.py", line 128, in _render
rv = template.render(context)
File "C:\Users\nmyle\anaconda3\envs\py\Lib\site-packages\jinja2\environment.py", line 1291, in render
self.environment.handle_exception()
File "C:\Users\nmyle\anaconda3\envs\py\Lib\site-packages\jinja2\environment.py", line 925, in handle_exception
raise rewrite_traceback_stack(source=source)
File "C:\Users\nmyle\OneDrive\Desktop\flaskcodeusethis\flaskblog2\app\templates\home.html", line 1, in top-level template code
{% extends "layout.html" %}
File "C:\Users\nmyle\OneDrive\Desktop\flaskcodeusethis\flaskblog2\app\templates\layout.html", line 21, in top-level template code
<h2> Click Here to donate </h2>
File "C:\Users\nmyle\anaconda3\envs\py\Lib\site-packages\flask\helpers.py", line 338, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "C:\Users\nmyle\anaconda3\envs\py\Lib\site-packages\flask\helpers.py", line 325, in url_for
rv = url_adapter.build(
File "C:\Users\nmyle\anaconda3\envs\py\Lib\site-packages\werkzeug\routing.py", line 2315, in build
raise BuildError(endpoint, values, method, self)
werkzeug.routing.BuildError: Could not build url for endpoint 'stripe_payment/userinfo.donations'. Did you mean 'userinfo.login' instead?

The parameter passed to url_for references the name of the blueprint followed by the identifier of the endpoint, separated by a period. The name of the blueprint is the first string passed when the instance is created. The subfolder doesn't matter.
url_for('userinfo.donations')
You only need to specify the subfolder within the template directory when calling render_template. Here you refer to the file to be rendered.
render_template('stripe_payment/donations.html', **locals())

Related

AttributeError: 'Test' object has no attribute '__name__'

This is the app.py. i faced this problem on my main project so i created a spearate test project to test it. and it occures again. here i tried to make a database in mongo then create a form out of it. pretty straight forward but no idea why the error happend
from flask_mongoengine.wtf import model_form
from flask_mongoengine import MongoEngine
from flask import render_template,request,Blueprint,Flask
app=Flask(__name__)
db= MongoEngine()
app.config\['MONGODB_SETTINGS'\]={'db':'project_database','host':'localhost','port':27017,'alias':'default'}
\#assign app to database
db.init_app(app)
class Test1(db.Document):
in1=db.StringField()
in2=db.StringField()
in3=db.StringField()
#app.route('/',methods=\['GET','POST'\])
def index():
test=model_form(Test1())
return render_template('inedx.html',test=test)
app.run(debug=True)
This is the error
Traceback (most recent call last):
File "C:\Users\Give Up\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 2548, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\Give Up\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 2528, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\Give Up\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Give Up\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Give Up\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Give Up\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "g:\Documents\onedrive\OneDrive - MSFT\Huzaifa\CODE\TESST\asdasdasdasd\app.py", line 25, in index
test=model_form(Test1())
File "C:\Users\Give Up\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_mongoengine\wtf\orm.py", line 306, in model_form
return type(model.__name__ + "Form", (base_class,), field_dict)
AttributeError: 'Test1' object has no attribute '__name__'
I wanted to make a ModelForm from Mongo Document. But I have no idea what is the problem
Found the solution. pretty dumb that I didn't notice. but here is the right way
def index():
test=model_form(Test1)
test=test()
return render_template('inedx.html',test=test)

Internal Server Error when uploading a file using Flask

I am developing a web app with Flask using CS50 IDE. I want the user to upload a file with a form. But when the form is submitted, I get a "500 Internal Server Error", whether a file is selected on not.
If a file is selected, there are no error logs in the console.
If NO file is selected, there is the following error log:
ERROR:application:Exception on /new-item [POST]
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/ubuntu/final-project/helpers.py", line 34, in decorated_function
return f(*args, **kwargs)
File "/home/ubuntu/final-project/application.py", line 45, in decorated_function
return f(*args, **kwargs)
File "/home/ubuntu/final-project/application.py", line 350, in newItem
file.save(os.path.join(app.config['IMAGE_UPLOADS'], filename))
File "/usr/local/lib/python3.7/site-packages/werkzeug/datastructures.py", line 2800, in save
dst = open(dst, "wb")
IsADirectoryError: [Errno 21] Is a directory: 'static/img/menu/'
Flask code
app.config["IMAGE_UPLOADS"] = "static/img/menu/"
#app.route("/new-item", methods=['GET', 'POST'])
def newItem():
if request.method == "POST":
if request.files:
file = request.files["file"]
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['IMAGE_UPLOADS'], filename))
HTML code
<form action="/new-item" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file">
<label>Choose Image</label>
</div>
<button type="submit">Submit</button>
</form>
Any idea what's causing the error?
You need to remove the trailing slash, this is a misuse of os.path.join
app.config["IMAGE_UPLOADS"] = "static/img/menu" # drop the trailing slash
See Why doesn't os.path.join() work in this case?
You may also need to update app.config["IMAGE_UPLOADS"] to be an absolute path instead of a relative path.

Custom tags work every other time django?

I did the calf's ear. forgive me for asking this stupid question.
*The error has been found, I try to load the function with my load when it's not the function that is loaded but the py file.
*update add directory tree
I'm in total misunderstanding, I created custom tags for my project. I had a hard time to get them accepted by django (I had to reboot my local server several times) finally it worked here I save a new custom tag, but I can't load it in django, it tells me that the tag doesn't exist. I restarted several times. I even made a copy of my previous code by simply changing the name of the function but I can't get django to take it, it tells me that it doesn't exist...
Thank you in advance :)
in application > templatetags with init file etc...
in template use :
{% load tags_blog tags_files %} work
{% load background_image %} doesn't work The first two custom tags work
Work tag loaded in django :(base.html)
register = template.Library()
#register.simple_tag()
def news_archive_date_blog():
list_all_year = New.all_year_post()
if len(list_all_year) > 1:
list_all_year.remove(timezone.now().year)
return list_all_year
#register.simple_tag()
def rallies_archive_date_blog():
list_all_year = Rally.all_year_post()
if len(list_all_year) > 1:
list_all_year.remove(timezone.now().year)
return list_all_year
no work (TemplateSyntaxError at /'background_image' is not a registered tag library.)(base.html)
#register.simple_tag()
def background_image():
list_all_year = Rally.all_year_post()
if len(list_all_year) > 1:
list_all_year.remove(timezone.now().year)
return list_all_year
bmvt:
bmvt
blog:
templatetags
init
tags_blogs
models
django.template.exceptions.TemplateSyntaxError
django.template.exceptions.TemplateSyntaxError: 'backgroundimage' is
not a registered tag library. Must be one of: account admin_list
admin_modify admin_static admin_urls cache compress crispy_forms_field
crispy_forms_filters crispy_forms_tags crispy_forms_utils
debugger_tags highlighting hitcount_tags i18n indent_text l10n log pwa
rest_framework socialaccount solo_tags static staticfiles syntax_color
tags_blog tags_files truncate_letters tz widont
Traceback (most recent call last) File
"/usr/local/lib/python3.7/site-packages/django/template/defaulttags.py",
line 1021, in find_library return parser.libraries[name] During
handling of the above exception, another exception occurred: File
"/usr/local/lib/python3.7/site-packages/django/contrib/staticfiles/handlers.py",
line 65, in call return self.application(environ, start_response)
File
"/usr/local/lib/python3.7/site-packages/django/core/handlers/wsgi.py",
line 141, in call response = self.get_response(request) File
"/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py",
line 75, in get_response response = self._middleware_chain(request)
File
"/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py",
line 36, in inner response = response_for_exception(request, exc) File
"/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py",
line 90, in response_for_exception response =
handle_uncaught_exception(request, get_resolver(get_urlconf()),
sys.exc_info()) File
"/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py",
line 125, in handle_uncaught_exception return
debug.technical_500_response(request, *exc_info) File
"/usr/local/lib/python3.7/site-packages/django_extensions/management/technical_response.py", line 37, in null_technical_500_response six.reraise(exc_type,
exc_value, tb) File "/usr/local/lib/python3.7/site-packages/six.py",
line 695, in reraise raise value.with_traceback(tb) File
"/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py",
line 34, in inner response = get_response(request) File
"/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py",
line 145, in _get_response response =
self.process_exception_by_middleware(e, request) File
"/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py",
line 143, in _get_response response = response.render() File
"/usr/local/lib/python3.7/site-packages/django/template/response.py",
line 106, in render self.content = self.rendered_content File
"/usr/local/lib/python3.7/site-packages/django/template/response.py",
line 81, in rendered_content template =
self.resolve_template(self.template_name) File
"/usr/local/lib/python3.7/site-packages/django/template/response.py",
line 63, in resolve_template return select_template(template,
using=self.using) File
"/usr/local/lib/python3.7/site-packages/django/template/loader.py",
line 42, in select_template return engine.get_template(template_name)
File
"/usr/local/lib/python3.7/site-packages/django/template/backends/django.py",
line 34, in get_template return
Template(self.engine.get_template(template_name), self) File
"/usr/local/lib/python3.7/site-packages/django/template/engine.py",
line 143, in get_template template, origin =
self.find_template(template_name) File
"/usr/local/lib/python3.7/site-packages/django/template/engine.py",
line 125, in find_template template = loader.get_template(name,
skip=skip) File
"/usr/local/lib/python3.7/site-packages/django/template/loaders/base.py",
line 30, in get_template contents, origin, origin.template_name,
self.engine, File
"/usr/local/lib/python3.7/site-packages/django/template/base.py", line
156, in init self.nodelist = self.compile_nodelist() File
"/usr/local/lib/python3.7/site-packages/django/template/base.py", line
194, in compile_nodelist return parser.parse() File
"/usr/local/lib/python3.7/site-packages/django/template/base.py", line
478, in parse raise self.error(token, e) File
"/usr/local/lib/python3.7/site-packages/django/template/base.py", line
476, in parse compiled_result = compile_func(self, token) File
"/usr/local/lib/python3.7/site-packages/django/template/loader_tags.py",
line 266, in do_extends nodelist = parser.parse() File
"/usr/local/lib/python3.7/site-packages/django/template/base.py", line
478, in parse raise self.error(token, e) File
"/usr/local/lib/python3.7/site-packages/django/template/base.py", line
476, in parse compiled_result = compile_func(self, token) File
"/usr/local/lib/python3.7/site-packages/django/template/defaulttags.py",
line 1078, in load lib = find_library(parser, name) File
"/usr/local/lib/python3.7/site-packages/django/template/defaulttags.py",
line 1025, in find_library name, "\n".join(sorted(parser.libraries)),
django.template.exceptions.TemplateSyntaxError: 'backgroundimage' is
not a registered tag library. Must be one of: account admin_list
admin_modify admin_static admin_urls cache compress crispy_forms_field
crispy_forms_filters crispy_forms_tags crispy_forms_utils
debugger_tags highlighting hitcount_tags i18n indent_text l10n log pwa
rest_framework socialaccount solo_tags static staticfiles syntax_color
tags_blog tags_files truncate_letters tz widont
Well, I have someone who made me understand my totally stupid mistake, I'm trying to use the {% load %} tag on a function when it's the .py file that's loaded so I have to load the file once and use the tags afterwards.

custom 404 error page in django 1.5

I was trying to develop a custom 404 error page in my django website. I implemented everything as per this link. But then a problem occurred when I tried it with an invalid url.
TemplateDoesNotExist: 500-page.html
handler500 = 'polls.views.error500' instead of mysite.views.error500 why it is not recognising my template.
As per the link I placed the 500-page html on the root templates folder.
My error
Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "/home/anuj/Envs/estoppeleasy/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 255, in __call__
response = self.get_response(request)
File "/home/anuj/Envs/estoppeleasy/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 156, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/home/anuj/Envs/estoppeleasy/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 224, in handle_uncaught_exception
return callback(request, **param_dict)
File "/home/anuj/Envs/estoppeleasy/letterproject/estoppeleasy/web/views.py", line 68, in error500
return render(request,'500-page.html')
File "/home/anuj/Envs/estoppeleasy/local/lib/python2.7/site-packages/django/shortcuts/__init__.py", line 53, in render
return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/home/anuj/Envs/estoppeleasy/local/lib/python2.7/site-packages/django/template/loader.py", line 170, in render_to_string
t = get_template(template_name)
File "/home/anuj/Envs/estoppeleasy/local/lib/python2.7/site-packages/django/template/loader.py", line 146, in get_template
template, origin = find_template(template_name)
File "/home/anuj/Envs/estoppeleasy/local/lib/python2.7/site-packages/django/template/loader.py", line 139, in find_template
raise TemplateDoesNotExist(name)
TemplateDoesNotExist: 500-page.html
You template should be named 500.html and 404.html not 500-page.html. You don't need any extra views for this. It all works out of the box. Remove all extra stuff you may have added to your urls.py, settings.py or views.py regarding to the 500 error.
Just and only put a 500.html file into your templates-root folder.
Keep in mind to NOT extend your base.html. Create a fresh clean self-running html file without any includes or extends.
Create templates named 500.html and 404.html and place in root folder of template directory and it will work.

django, gravatar - add_to_builtins('gravatar.gravatar') causes crash on page load

add_to_builtins('gravatar.gravatar')
is being used in my settings.py file, and it causes a crash on page load with this error:
Traceback (most recent call last):
File "C:\development\python\Lib\site-packages\django\core\servers\basehttp.py", line 283, in run
self.result = application(self.environ, self.start_response)
File "C:\development\python\Lib\site-packages\django\contrib\staticfiles\handlers.py", line 68, in call
return self.application(environ, start_response)
File "C:\development\python\Lib\site-packages\django\core\handlers\wsgi.py", line 272, in call
response = self.get_response(request)
File "C:\development\python\Lib\site-packages\django\core\handlers\base.py", line 169, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "C:\development\python\Lib\site-packages\django\core\handlers\base.py", line 203, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "C:\development\python\Lib\site-packages\django\views\debug.py", line 59, in technical_500_response
html = reporter.get_traceback_html()
File "C:\development\python\Lib\site-packages\django\views\debug.py", line 128, in get_traceback_html
t = Template(TECHNICAL_500_TEMPLATE, name='Technical 500 template')
File "C:\development\python\Lib\site-packages\django\template\base.py", line 108, in init
self.nodelist = compile_string(template_string, origin)
File "C:\development\python\Lib\site-packages\django\template\base.py", line 135, in compile_string
parser = parser_class(lexer.tokenize())
File "C:\development\python\Lib\site-packages\django\template\debug.py", line 34, in init
super(DebugParser, self).init(lexer)
File "C:\development\python\Lib\site-packages\django\template\base.py", line 208, in init
print lib.tags
AttributeError: 'NoneType' object has no attribute 'tags'
If i don't have any issue with using gravatar if i don't use the add_to_builtins functionality - that is, with plain old load tags in my views. I'm just using it a fair bit, so thought i might make use of the add_to_builtins functionality.
From the looks of things, the imported version crashes because the import_library(module) for gravatar.gravatar returns None (i know this because i printed out that line, and it returns None) - what is wrong with what i've done?
oh gravatar.
Ok, so i was all wrong in how to import this using the add_to_builtins - what i needed to do was:
add_to_builtins('gravatar.templatetags.gravatar')
i'm unsure as to why, but that works a treat. Now i don't need to have any messy "load" statements, and i can happily call
{% gravatar story.user 40 %}
from any of my templates. yay!