Problem with initiating form fields as instance variables in form classes - python-3.x

Not able to have a instance variable of WTForm fields as instance variables
This is to have multiple number (flexible) of field which can be cascaded to increase number of fields.
The program is working fine for a simple class and one login field and one password field if the field are class variables..
project/app/froms.py
class LoginForm(FlaskForm):
username = StringField('Username')
password = PasswordField('Password')
if the fields are initiated in the constructors, the program is not working. the error of the program is
project/app/forms.py
class TestLoginForm(FlaskForm):
def __init__(self):
username = StringField('Username')
password = PasswordField('Password')
the following are other parts of this program
<!-- project/app/templates/test.html -->
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Sign In</h1>
<form method="post" novalidate>
{{ form.hidden_tag() }}
<p>
{{ form.username.label }}<br>
{{ form.username(size=32) }}
</p>
<p>
{{ form.password.label }}<br>
{{ form.password(size=32) }}
</p>
<p>{{ form.submit() }}</p>
</form>
</body>
</html>
project/app/routes.py
from app import app
from flask import render_template
from app.forms import TestLoginForm
#app.route('/', methods=['GET','POST'])
#app.route('/login', methods=['GET','POST'])
def index():
form = TestLoginForm()
return render_template('test.html', form=form)
project/app/init.py
from flask import Flask
app = Flask(__name__)
app.config['SECRET_KEY'] = 'you-will-never-guess'
from app import routes
project/ website.py
from app import app
Please let me know what are the concepts I need to learn and advise about possible way to get the outcome of the problem.
Traceback (most recent call last):
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\css120807\Documents\Flask_testWebsite\app\routes.py", line 13, in index
return render_template('test.html', form=form)
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\templating.py", line 135, in render_template
context, ctx.app)
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\templating.py", line 117, in _render
rv = template.render(context)
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\jinja2\asyncsupport.py", line 76, in render
return original_render(self, *args, **kwargs)
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\jinja2\environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\jinja2\_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "C:\Users\css120807\Documents\Flask_testWebsite\app\templates\test.html", line 10, in top-level template code
{{ form.hidden_tag() }}
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask_wtf\form.py", line 135, in hidden_tag
u'\n'.join(text_type(f) for f in hidden_fields(fields or self))
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask_wtf\form.py", line 135, in <genexpr>
u'\n'.join(text_type(f) for f in hidden_fields(fields or self))
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\flask_wtf\form.py", line 125, in hidden_fields
for f in fields:
File "C:\Users\css120807\AppData\Local\Continuum\anaconda3\lib\site-packages\wtforms\form.py", line 57, in __iter__
return iter(itervalues(self._fields))
AttributeError: 'TestLoginForm' object has no attribute '_fields'

In quickstart there is an example of creating forms:
https://flask-wtf.readthedocs.io/en/stable/quickstart.html#creating-forms
There are class fields, not instance (in __init__).
If I understand correctly you would like to inherit fields from parent class, why not like this:
class MyForm(FlaskForm):
name = StringField('name', validators=[DataRequired()])
class AnotherForm(MyForm):
surname = StringField('surname', validators=[DataRequired()])
then you can use two forms in your routes.py:
form = MyForm()
with csrf token and name field
or
form = AnotherForm()
with everything from MyForm (csrf + name) and surname

Related

zipfile.BadZipFile: Bad magic number for central directory

I am trying to read an excel file in the backened (flask) sent from the frontend (angularjs). However, I am getting the error
File "/var/task/pandas/util/_decorators.py", line 296, in wrapper
return func(*args, **kwargs)
File "/var/task/pandas/io/excel/_base.py", line 304, in read_excel
io = ExcelFile(io, engine=engine)
File "/var/task/pandas/io/excel/_base.py", line 867, in __init__
self._reader = self._engines[engine](self._io)
File "/var/task/pandas/io/excel/_openpyxl.py", line 480, in __init__
super().__init__(filepath_or_buffer)
File "/var/task/pandas/io/excel/_base.py", line 351, in __init__
self.book = self.load_workbook(filepath_or_buffer)
File "/var/task/pandas/io/excel/_openpyxl.py", line 491, in load_workbook
return load_workbook(
File "/mnt/accesspoint/openpyxl/reader/excel.py", line 315, in load_workbook
reader = ExcelReader(filename, read_only, keep_vba,
File "/mnt/accesspoint/openpyxl/reader/excel.py", line 124, in __init__
self.archive = _validate_archive(fn)
File "/mnt/accesspoint/openpyxl/reader/excel.py", line 96, in _validate_archive
archive = ZipFile(filename, 'r')
File "/var/lang/lib/python3.8/zipfile.py", line 1269, in __init__
self._RealGetContents()
File "/var/lang/lib/python3.8/zipfile.py", line 1364, in _RealGetContents
raise BadZipFile("Bad magic number for central directory")
zipfile.BadZipFile: Bad magic number for central directory
What is the problem that's causing this?
Angularjs html
<nz-card nzTitle="Upload File" bordered={false} style="flex: 1 1 auto;">
<nz-upload
[nzCustomRequest]="handleUpload"
(nzChange)="handleChange($event)"
>
<p class="ant-upload-drag-icon"><i nz-icon nzType="inbox"></i></p>
<p class="ant-upload-text">
Click or drag CSV/Excel a file to this area to upload
</p>
</nz-upload>
</nz-card>
Angularjs component
handleUpload = (item: any) => {
const formData = new FormData();
formData.append(item.name, item.file);
const headers = new HttpHeaders();
headers.set('Content-Type', 'multipart/form-data');
var upload = this.httpClient.post(this.SERVER_URL, formData,{headers: headers}).subscribe(
(res) => {
console.log("success");
}
Flask python
def upload():
file = request.files['file']
print("request", file)
df = pd.read_excel(file, index_col=0, engine='openpyxl')
print(df)
Logs (before the error message)
request <FileStorage: 'sample_excel.xlsx' ('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')>
I have also tried reading it using with
with open(file, 'rb') as f
But with that I get an error stating TypeError: expected str, bytes or os.PathLike object, not FileStorage
Any help would be greatly appreciated!!

Can't figure out why I'm getting `Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found` in a django project

The project has 2 apps - accounts (very basic custom users) and portal.
myproject/myproject/urls.py:
from django.contrib import admin
from django import urls
from portal import admin as user_admin
from portal import views
urlpatterns = [
urls.path(r'admin/', admin.site.urls),
urls.path(r'portal/mymodel/', views.testview),
urls.path('', user_admin.user_site.urls),
]
myproject/portal/templates/portal/mymodel/testview.html:
{% extends "admin/change_list.html" %}
{% block after_field_sets %}{{ block.super }}
<h2> hello world </h2>
{% endblock %}
change_list.html (built-in django template):
{% extends "admin/base_site.html" %}
{% load i18n admin_urls static admin_list %}
{% block extrastyle %}
{{ block.super }}
<link rel="stylesheet" type="text/css" href="{% static "admin/css/changelists.css" %}">
{% if cl.formset %}
<link rel="stylesheet" type="text/css" href="{% static "admin/css/forms.css" %}">
{% endif %}
{% if cl.formset or action_form %}
<script src="{% url 'admin:jsi18n' %}"></script>
{% endif %}
{{ media.css }}
{% if not actions_on_top and not actions_on_bottom %}
<style>
#changelist table thead th:first-child {width: inherit}
</style>
{% endif %}
{% endblock %}
{% block extrahead %}
{{ block.super }}
{{ media.js }}
{% endblock %}
{% block bodyclass %}{{ block.super }} app-{{ opts.app_label }} model-{{ opts.model_name }} change-list{% endblock %}
{% if not is_popup %}
{% block breadcrumbs %}
<div class="breadcrumbs">
{% translate 'Home' %}
› {{ cl.opts.app_config.verbose_name }}
› {{ cl.opts.verbose_name_plural|capfirst }}
</div>
{% endblock %}
{% endif %}
{% block coltype %}{% endblock %}
{% block content %}
<div id="content-main">
{% block object-tools %}
<ul class="object-tools">
{% block object-tools-items %}
{% change_list_object_tools %}
{% endblock %}
</ul>
{% endblock %}
{% if cl.formset and cl.formset.errors %}
<p class="errornote">
{% if cl.formset.total_error_count == 1 %}{% translate "Please correct the error below." %}{% else %}{% translate "Please correct the errors below." %}{% endif %}
</p>
{{ cl.formset.non_form_errors }}
{% endif %}
<div class="module{% if cl.has_filters %} filtered{% endif %}" id="changelist">
<div class="changelist-form-container">
{% block search %}{% search_form cl %}{% endblock %}
{% block date_hierarchy %}{% if cl.date_hierarchy %}{% date_hierarchy cl %}{% endif %}{% endblock %}
<form id="changelist-form" method="post"{% if cl.formset and cl.formset.is_multipart %} enctype="multipart/form-data"{% endif %} novalidate>{% csrf_token %}
{% if cl.formset %}
<div>{{ cl.formset.management_form }}</div>
{% endif %}
{% block result_list %}
{% if action_form and actions_on_top and cl.show_admin_actions %}{% admin_actions %}{% endif %}
{% result_list cl %}
{% if action_form and actions_on_bottom and cl.show_admin_actions %}{% admin_actions %}{% endif %}
{% endblock %}
{% block pagination %}{% pagination cl %}{% endblock %}
</form>
</div>
{% block filters %}
{% if cl.has_filters %}
<div id="changelist-filter">
<h2>{% translate 'Filter' %}</h2>
{% if cl.has_active_filters %}<h3 id="changelist-filter-clear">
✖ {% translate "Clear all filters" %}
</h3>{% endif %}
{% for spec in cl.filter_specs %}{% admin_list_filter cl spec %}{% endfor %}
</div>
{% endif %}
{% endblock %}
</div>
</div>
{% endblock %}
myproject/portal/templates/portal/views.py:
from django.shortcuts import render
def testview(request):
return render(
request, 'portal/mymodel/testview.html', {'app_label': 'portal'}
)
and the stacktrace:
Traceback (most recent call last):
File "/usr/local/Cellar/python#3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/wsgiref/handlers.py", line 137, in run
self.result = application(self.environ, self.start_response)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/contrib/staticfiles/handlers.py", line 76, in __call__
return self.application(environ, start_response)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 133, in __call__
response = self.get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 130, in get_response
response = self._middleware_chain(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner
response = response_for_exception(request, exc)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__
response = response or self.get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner
response = response_for_exception(request, exc)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__
response = response or self.get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner
response = response_for_exception(request, exc)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__
response = response or self.get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner
response = response_for_exception(request, exc)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__
response = response or self.get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner
response = response_for_exception(request, exc)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__
response = response or self.get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner
response = response_for_exception(request, exc)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__
response = response or self.get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner
response = response_for_exception(request, exc)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__
response = response or self.get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner
response = response_for_exception(request, exc)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Me:D/myproject/myproject/portal/views.py", line 8, in testview
return render(
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 170, in render
return self._render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/defaulttags.py", line 312, in render
return nodelist.render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/template/defaulttags.py", line 446, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/urls/base.py", line 86, in reverse
return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 694, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>portal|auth|accounts)/$']
Does anyone know what I'm doing wrong? Stupid beginner mistake? Also if there's other code that may be relevant here please let me know and I can provide it.
Edited to add:
The higher level issue here is that MyModel has a field called user. When a user views the MyModel changelist, they need to only see the MyModel objects that reference them, and should not see the MyModel objects that reference other users.
First, you are using a view outside of the admin, which is fine, but you are using an admin template change_list.html which assumes some variables sent out with the template context. I would suggest to add custom urls to your admin.py (see bellow), and send the necessary context so the template is rendered properly.
I had the same issue, which was caused in this line:
<li>{{ opts.app_config.verbose_name }}</li>
When looking on the context provided to the template with django-debug-toolbar I noticed that the opts variable was not being sent. In your case, the culprit is probably cl.
So I had to update my custom urls code and sent it myself:
def get_urls(self):
urls = super().get_urls()
opts = self.model._meta
custom_urls = [
url(
r'^(?P<some_id>.+)/actions/task_start/$',
self.admin_site.admin_view(SomeCustomFormView.as_view(
extra_context={'opts': opts}
)),
name='task_start',
),
]
return custom_urls + urls
The cl variable is got from the request:
cl = self.get_changelist_instance(request) and sent out with the context like this (django/contrib/admin/options.py):
context = {
**self.admin_site.each_context(request),
'module_name': str(opts.verbose_name_plural),
'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
'selection_note_all': selection_note_all % {'total_count': cl.result_count},
'title': cl.title,
'subtitle': None,
'is_popup': cl.is_popup,
'to_field': cl.to_field,
'cl': cl,
'media': media,
'has_add_permission': self.has_add_permission(request),
'opts': cl.opts,
'action_form': action_form,
'actions_on_top': self.actions_on_top,
'actions_on_bottom': self.actions_on_bottom,
'actions_selection_counter': self.actions_selection_counter,
'preserved_filters': self.get_preserved_filters(request),
**(extra_context or {}),
}
But you don't have easy access to the request in get_urls so I would change the template code and instead of using cl I would use opts which I get from the model meta field.

AttributeError at /logout/ 'tuple' object has no attribute 'backend'

I used Python3 in windows 10 to write a django2 web app.
I tried to configure the LDAP login, but failed.
When I test using postman, it could get the reply successfully.
That is, I send a request to https://example.com/staff, with some authentication code and payload containing username and password, and it reply me with the LDAP reply.
However, when I tried to using ldap3 in Django, after successfully login, error shows:
AttributeError at /logout/
'tuple' object has no attribute 'backend'
code:
settings.py:
AUTHENTICATION_BACKENDS = (
'app.backends.LDAPBackend',
('django.contrib.auth.backends.ModelBackend'),
)
app/backends.py:
from django.contrib.auth import get_user_model
UserModel = get_user_model()
class LDAPBackend:
def authenticate(self, request, username=None, password=None, **kwargs):
try:
headers = {'Authorization': xxxxx}
body = {"username": username, "password": password}
response = requests.post(url="https://example.com/staff", json=body, headers=headers)
result = response.json()
print(result)
if result['code'] != "OK":
logger.info("Wrong Login Information")
return None
print("connected")
except Exception as e:
print(e)
user = UserModel.objects.update_or_create(username=username)
return user
def get_user(self, user_id):
try:
return UserModel._default_manager.get(pk=user_id)
except UserModel.DoesNotExist:
return None
error shows: AttributeError at /logout/ 'tuple' object has no attribute 'backend', below shows result in console:
connected
Internal Server Error: /logout/
Traceback (most recent call last):
File "C:\Users\software\python\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\software\python\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\software\python\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\software\python\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\views\decorators\debug.py", line 76, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\contrib\auth\views.py", line 61, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\views\generic\edit.py", line 141, in post
if form.is_valid():
File "C:\Users\software\python\lib\site-packages\django\forms\forms.py", line 185, in is_valid
return self.is_bound and not self.errors
File "C:\Users\software\python\lib\site-packages\django\forms\forms.py", line 180, in errors
self.full_clean()
File "C:\Users\software\python\lib\site-packages\django\forms\forms.py", line 382, in full_clean
self._clean_form()
File "C:\Users\software\python\lib\site-packages\django\forms\forms.py", line 409, in _clean_form
cleaned_data = self.clean()
File "C:\Users\software\python\lib\site-packages\django\contrib\auth\forms.py", line 205, in clean
self.user_cache = authenticate(self.request, username=username, password=password)
File "C:\Users\software\python\lib\site-packages\django\contrib\auth\__init__.py", line 80, in authenticate
user.backend = backend_path
AttributeError: 'tuple' object has no attribute 'backend'
[22/Mar/2021 09:49:10] "POST /logout/ HTTP/1.1" 500 149071
You write the following line:
user = UserModel.objects.update_or_create(username=username)
The update_or_create method returns a tuple with the object and a boolean with whether the object was created. So you are storing this tuple in the variable user and returning that. But authenticate is supposed to return only the user causing unintended effects leading to an error. Also you should be using get_or_create [Django docs] instead of update_or_create.
So you should change that above line to:
user, created = UserModel.objects.get_or_create(username=username)

Flask. Processing a form on another page. TypeError: The view function did not return a valid response

Good day!
I'm new to Python and Flask
I am trying to render a form on another page when I apply this construction :
#app.route('/tools', methods=['POST', 'GET'])
def tools():
"""Form Create Users"""
createadduser_form = ToolsAddUser()
return render_template("tools.html", title='Admin Tools', **locals())
#app.route('/createuser', methods=["GET", "POST"])
def createuser():
if request.method == 'POST':
adduser_clientid = request.form["adduser_clientid"]
adduser_value = request.form["adduser_value"]
create(adduser_clientid, adduser_value)
return redirect("tools")
But in the event that I use another one with field validation, it does not work:
#app.route('/tools', methods=['POST', 'GET'])
def tools():
createadduser_form = ToolsAddUser()
return render_template("tools.html", title='Admin Tools', **locals())
#app.route('/createuser', methods=["GET", "POST"])
def createuser():
createadduser_form = ToolsAddUser()
if createadduser_form.validate_on_submit():
adduser_clientid = request.form["adduser_clientid"]
adduser_value = request.form["adduser_value"]
create(adduser_clientid, adduser_value)
return redirect("tools")
I understand the problem here:
if createadduser_form.validate_on_submit():
if request.method == 'POST':
In the first option, when you click on the button, the script works as needed (the script is launched powershell, so do not pay attention to the names of the variables, this is a test)))) everything works well
In the second option, it shows an error:
I can't understand what the problem is, little experience. I would be very grateful for your help.
http://127.0.0.1:5000/createuser
TypeError
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
Traceback (most recent call last)
File "E:\Project\web\venv\lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "E:\Project\web\venv\lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "E:\Project\web\venv\lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "E:\Project\web\venv\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "E:\Project\web\venv\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "E:\Project\web\venv\lib\site-packages\flask\app.py", line 1953, in full_dispatch_request
return self.finalize_request(rv)
File "E:\Project\web\venv\lib\site-packages\flask\app.py", line 1968, in finalize_request
response = self.make_response(rv)
File "E:\Project\web\venv\lib\site-packages\flask\app.py", line 2098, in make_response
"The view function did not return a valid response. The"
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
Below, just in case, the form itself...
class ToolsAddUser(FlaskForm):
adduser_clientid = StringField('Client ID',
validators=[DataRequired()],
render_kw={'class': 'form-control',
'placeholder': 'Client ID'})
adduser_value = StringField('Value',
validators=[DataRequired()],
render_kw={'class': 'form-control',
'placeholder': 'Value'})
submitbuttonuser = SubmitField('Submit',
render_kw={'class': 'btn btn-dark'})
I apologize for the inaccuracies in the wording
<form action="/createuser" method="post">
 <div class="form-group form shadow">
 <label for="">
 <h5>Add User</h5>
 </label>
 {{ createadduser_form.adduser_clientid }}<br>
 {{ createadduser_form.adduser_value }}<br>
 <input type="text" class="form-control" placeholder="Example input" style="visibility: hidden;"><br>
 {{ createadduser_form.submitbuttonuser }}
 </div>
</form>
You're not returning a response when you navigate to /createuser, which will be a GET. You are only returning a response within if createadduser_form.validate_on_submit():, which will only handle the POST call.
I assume you'll be wanting to render the form you've created, like:
return render_template("createuser.html")
Thank you all who paid attention to this topic, I have solved my problem. The thing is that I didn't add the cars page to the html
It turns out that the CSRF check did not pass my request further than the page
{{ {{ create add user_form.hidden_tag () }}
For this check, it is required
if create add user_form.validate_on_submit():
Week, week, week

Flask-Login: AttributeError: 'int' object has no attribute 'is_authenticated'

I am using python3 with Flask 1.1.1 and Werkzeug 0.16.0.
I am trying to use the Flask login manager to manage the user sessions.
For the DB am running sqlite3.
Below is the class definition
class UserData(UserMixin):
def __init__(self, username, password):
self.username = username
self.password = password
self._authenticated = False
def is_authenticated(self):
return self._authenticated
def is_active(self):
return True
# return true if user is activte and authenticated
def is_annonymous(self):
return False
# return true if annon, actual user return false
def get_id(self):
global connection
user_id = get_user_id(self.username, connection)
unicode_user_id = load_user(user_id)
if unicode_user_id != 0:
self._authenticated = True
print("userid:" , unicode_user_id)
return unicode_user_id
In the function get_id , I fetch the user-id from the DB and set the self._authenticated flag for the authentication.
#login_manager.user_loader
def load_user(user_id):
return int(user_id)
The below is the protected page which should be accessed only but authorized users.
#app.route('/device_detail', methods=['GET', 'POST'])
#login_required
def device_detail_operation():
error = None
return render_template('device_detail.html', error=error)
After the user login when I try to access the protected page directly am running into attribute error.
Below is a stack trace
127.0.0.1 - - [11/Dec/2019 22:52:26] "GET /device_detail HTTP/1.1" 500 -
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2328, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2314, in wsgi_app
response = self.handle_exception(e)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1760, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 36, in reraise
raise value
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2311, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1834, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1737, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 36, in reraise
raise value
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1832, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1818, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python3.7/site-packages/flask_login/utils.py", line 259, in decorated_view
elif not current_user.is_authenticated:
File "/usr/local/lib/python3.7/site-packages/werkzeug/local.py", line 348, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: 'int' object has no attribute 'is_authenticated'
In load_user function, you need to return user object. I did not use sqlite but i guess that have something like that: user = models.User.query().filter(models.User.email == user_id).get()
#login_manager.user_loader
def load_user(user_id):
user = models.User.query().filter(models.User.email == user_id).get()
return user

Resources