Is it possible to use Template Tags in Django 1.11 to get around a "NoneType" Error? - django-template-filters

I am using template tags to present data that has been derived from class objects on the back end. Both class objects require inputs from the user to work and if the input is not valid they return None.
I need to present a difference calculation of two of the objects on the page (it does not need to be saved to the database). So I have installed mathfilters https://pypi.python.org/pypi/django-mathfilters to do the subtraction which worked if there is user input but does not work if I am just navigating to the page or no user input.
Template HTML:
<tr>
<td>Interest</td>
<td class="data">${{int_numbers.get_sum_int_daily_numbers | intcomma }}</td>
<td class="data">${{int_goals.get_div_goalsint_wdays | intcomma }}</td>
<td class="data"><font class="red">
${{ int_numbers.get_sum_int_daily_numbers|sub:int_goals.get_div_goalsint_wdays | intcomma }}
</font>
</td>
</tr>
Which gives me this error:
Traceback:
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in _resolve_lookup
882. current = current[bit]
During handling of the above exception ('NoneType' object is not subscriptable), another exception occurred:
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in _resolve_lookup
890. current = getattr(current, bit)
During handling of the above exception ('NoneType' object has no attribute 'get_div_goalsint_wdays'), another exception occurred:
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in _resolve_lookup
896. current = current[int(bit)]
During handling of the above exception (invalid literal for int() with base 10: 'get_div_goalsint_wdays'), another exception occurred:
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\DevProj\am\amreports\reports\views.py" in goals_view
61. 'int_monthtodate': int_monthtodate_goals,
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\shortcuts.py" in render
30. content = loader.render_to_string(template_name, context, request, using=using)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\loader.py" in render_to_string
68. return template.render(context, request)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\backends\django.py" in render
66. return self.template.render(context)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in render
207. return self._render(context)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in _render
199. return self.nodelist.render(context)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in render
990. bit = node.render_annotated(context)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in render_annotated
957. return self.render(context)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\loader_tags.py" in render
177. return compiled_parent._render(context)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in _render
199. return self.nodelist.render(context)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in render
990. bit = node.render_annotated(context)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in render_annotated
957. return self.render(context)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\loader_tags.py" in render
72. result = block.nodelist.render(context)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in render
990. bit = node.render_annotated(context)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in render_annotated
957. return self.render(context)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in render
1040. output = self.filter_expression.resolve(context)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in resolve
730. arg_vals.append(arg.resolve(context))
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in resolve
849. value = self._resolve_lookup(context)
File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\django\template\base.py" in _resolve_lookup
903. (bit, current)) # missing attribute
Exception Type: VariableDoesNotExist at /reports/goals/
Exception Value: Failed lookup for key [get_div_goalsint_wdays] in 'None'
I tried this filter:
<tr>
<td>Interest</td>
<td class="data">${{int_numbers.get_sum_int_daily_numbers | intcomma }}</td>
<td class="data">${{int_goals.get_div_goalsint_wdays | intcomma }}</td>
<td class="data"><font class="red">
{% if int_numbers.get_sum_int_daily_numbers|sub:int_goals.get_div_goalsint_wdays is "None" %}
0
{% else %}
${{ int_numbers.get_sum_int_daily_numbers|sub:int_goals.get_div_goalsint_wdays | intcomma }}
{% endif %}
</font>
</td>
</tr>
Received the same error.
Is there a way with template tags and filters to correct this issue?

Seems that "int_goals" is undefined, thus None. If you try to do a math operation on
int_numbers.get_sum_int_daily_numbers - None.get_div_goalsint_wdays python will throw an exception

Related

DRF Create: render_to_string() loses it's context variables when the Response is returned

Background
I want to create and render replies without the need to refresh the page. I know this can be done by submitting the form using AJAX or Fetch(), and use the returned response to append to the bottom of the comment list. I am trying to accomplish this using DRF and AJAX. I opted in to DRF HTMLRenderer + Django render_to_string() so I do not have to create a JS template literal to render the template from JSON, and it would also be a lot easier for me to make any template changes if I just let the Django templating system do it for me.
Problem
My response is not populating my template with context variables, despite me passing in the context to the built in render_to_string(). The chances of render_to_string() being at fault is very low, and I am honestly not sure how to resolve this. I also tried switching out the render_to_string() with render() to see if that would somehow fix the problem. However, the problem still remained.
I know this because of the following two attribute errors when viewing the response from the console:
'str' object has no attribute 'is_authenticated'
Reverse for 'profile_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['account/user/(?P<slug>[^/]+)/$']
Both of which would not be happening if the context was being evaluated in my template.
The actual reply itself is created and visible if I manually refresh the page after the AJAX post.
Information
There does not seem to be a problem with the actual context, because the break point shows the expected results (... is me replacing the actual text for brevity):
{'reply': <Reply: Reply object (47527)>, 'post': <Post: ....>, 'recipient': <Profile: ....>}}
Edit:
When I print print(response['render_reply']) the template is populated, however once it returns in return Response(response), the template is no longer populated with the reply object.
Questions
Is my problem happening with the render_to_string(), or is there something else at fault?
Am I on the right track to sending and rendering replies? Is there anything that can be improved? (code review)
So the problem is most likely occurring here, but that would be really odd because what are the chances of a built in function not working?
response['render_reply'] = render_to_string(
template_name=self.template_name, context=context, request=request
)
Relevant code
Viewset
I created my own action because I wasn't quite sure how to accomplish this with the default create().
class ReplyActionViewSet(viewsets.ModelViewSet):
queryset = Reply.objects.all()
serializer_class = ReplySerializer
permission_classes = [IsAuthenticated]
renderer_classes = [JSONRenderer, TemplateHTMLRenderer]
template_name = "post/partials/render-reply.html"
def get_queryset(self):
return self.queryset.filter(user=self.request.user)
#action(detail=True, methods=['post'])
def create_reply(self, request, pk=None):
response = {}
post = get_object_or_404(
Post.public_or_member_objects.all(), pk=pk
)
serializer = ReplySerializer(data=request.POST)
if serializer.is_valid():
...
reply = Reply.objects.create(**data)
...
context = {'reply': reply, 'post': post, 'data': {"post": post, "recipient": reply.recipient}}
response['render_reply'] = render_to_string(
template_name=self.template_name, context=context, request=request
)
return Response(response)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Snippet of the reply template where one of the issues is happening:
<div class="d-flex flex-row align-items-center">
<div class="avatar avatar-sm me-2" style="background-color:{{ post.user.avatar_color }};">
{{ reply.user.nickname|slice:1 }}
</div>
<a href="{% url "profile_detail" reply.user.username %}" class="text-decoration-none">
<span style="font-weight: 500; color:{{ post.user.avatar_color }};">{{ reply.user.nickname }}</span>
</a>
</div>
And here is my JS:
'use strict';
$(document).on("submit", ".js-reply-form", function (event) {
event.preventDefault();
const form = $(this);
const url = form.attr('action');
$.ajax({
type: "POST",
url: url,
dataType: 'html',
data: form.serialize(),
success: function (data) {
form.trigger('reset');
},
error: function (response) {
console.log(response);
console.log("failed!");
},
});
});
Included trace:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/api/v1/reply-actions/42874/create_reply/
Django Version: 3.2.7
Python Version: 3.10.2
Installed Applications:
Template error:
In template C:\Users\...\Documents\Repo\drf_project\journal\templates\journal\partials\reply-render-reply.html, error at line 36
'str' object has no attribute 'is_authenticated'
26 : </div>
27 :
28 : <div>
29 : {% if reply.user.is_premium %}
30 : <span title="{% trans "drf_project Premium" %}" class="px-1">
31 : <i class="fas fa-crown fa-fw"></i>
32 : </span>
33 : {% endif %}
34 :
35 : <span title="{% trans "X ratio" %}" class="px-1">
36 : <i class="fas fa-percentage"></i> {{ reply.user|get_X_ratio }}
37 : </span>
38 : </div>
39 : </div>
40 :
41 : <!-- Reply body -->
42 : <div>
43 : <div class="small text-muted my-2">{{ reply.date }}</div>
44 :
45 : <!-- Quoted content -->
46 : {% if reply.y_row_id %}
Traceback (most recent call last):
File "C:\Users\...\Documents\Repo\drf_project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\...\Documents\Repo\drf_project\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response
response = response.render()
File "C:\Users\...\Documents\Repo\drf_project\venv\lib\site-packages\django\template\response.py", line 105, in render
self.content = self.rendered_content
File "C:\Users\...\Documents\Repo\drf_project\venv\lib\site-packages\rest_framework\response.py", line 70, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "C:\Users\...\Documents\Repo\drf_project\venv\lib\site-packages\rest_framework\renderers.py", line 167, in render
return template.render(context, request=request)
File "C:\Users\...\Documents\Repo\drf_project\venv\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\...\Documents\Repo\drf_project\venv\lib\site-packages\django\template\base.py", line 170, in render
return self._render(context)
File "C:\Users\...\Documents\Repo\drf_project\venv\lib\site-packages\django\test\utils.py", line 100, in instrumented_test_render
return self.nodelist.render(context)
File "C:\Users\...\Documents\Repo\drf_project\venv\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\...\Documents\Repo\drf_project\venv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\...\Documents\Repo\drf_project\venv\lib\site-packages\django\template\base.py", line 988, in render
output = self.filter_expression.resolve(context)
File "C:\Users\...\Documents\Repo\drf_project\venv\lib\site-packages\django\template\base.py", line 698, in resolve
new_obj = func(obj, *arg_vals)
File "C:\Users\...\Documents\Repo\drf_project\journal\templatetags\navbar_tags.py", line 15, in get_X_ratio
if user.is_authenticated:
Exception Type: AttributeError at /api/v1/reply-actions/42874/create_reply/
Exception Value: 'str' object has no attribute 'is_authenticated'
Please post the whole trace for the 1st error
<str> object has no ...
Your 2nd error means that in
<a href="{% url "profile_detail" reply.user.username %}"
the username is empty.
The solution was honestly quite straightforward. response['render_reply'] evaluated to {'render_reply':'long string'} which is JSON.
So I needed to change the dataType in my AJAX post to use json instead of html.
I also just passed in the rendered template so I did not have to call data["render_reply"].
context = {
'reply': reply,
'post': post,
'recipient': reply.recipient
}
rendered_template = render_to_string(
template_name='journal/partials/reply-render-reply.html',
context=context,
request=request
)
return Response(rendered_template)

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.

Cannot resolve keyword 'name' into field. Choices are:

I'm Trying to filter through a model but everytime I tried this error keeps happening:
Exception Type: FieldError at /store/dashboard/utiles_dashboard/sliders/
Exception Value: Cannot resolve keyword 'name' into field. Choices are: id, image, order, slider, slider_id
here is part of the code:
views.py:
class SliderListView(SingleTableMixin, generic.TemplateView):
"""
Dashboard view of the slider list.
"""
template_name = 'oscar/dashboard/utiles_dashboard/slider_list.html'
form_class = SliderSearchForm
table_class = SliderTable
context_table_name = 'sliders'
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx['form'] = self.form
return ctx
def get_description(self, form):
if form.is_valid() and any(form.cleaned_data.values()):
return _('Resultado de busqueda de sliders')
return _('Sliders')
def get_table(self, **kwargs):
if 'recently_edited' in self.request.GET:
kwargs.update(dict(orderable=False))
table = super().get_table(**kwargs)
table.caption = self.get_description(self.form)
return table
def get_table_pagination(self, table):
return dict(per_page=20)
def get_queryset(self):
"""
Build the queryset for this list
"""
queryset = Slider.objects.all()
queryset = self.apply_search(queryset)
return queryset
def apply_search(self, queryset):
"""
Filter the queryset and set the description according to the search
parameters given
"""
self.form = self.form_class(self.request.GET)
if not self.form.is_valid():
return queryset
data = self.form.cleaned_data
if data.get('name'):
queryset = queryset.filter(name__icontains=data['name'])
return queryset
Forms.py:
class SliderSearchForm(forms.Form):
name = forms.CharField(max_length=255, required=False, label=_('Nombre'))
def clean(self):
cleaned_data = super().clean()
cleaned_data['name'] = cleaned_data['name'].strip()
return cleaned_data
slider_list.html:
{% extends 'oscar/dashboard/layout.html' %}
{% load i18n %}
{% load thumbnail %}
{% load static %}
{% load sorting_tags %}
{% load render_table from django_tables2 %}
{% block body_class %}{{ block.super }} catalogue{% endblock %}
{% block title %}
{% trans "Sliders" %} | {{ block.super }}
{% endblock %}
{% block breadcrumbs %}
<ul class="breadcrumb">
<li>
{% trans "Dashboard" %}
</li>
<li class="active">{% trans "Sliders" %}</li>
</ul>
{% endblock %}
{% block header %}
<div class="page-header action">
<i class="icon-plus"></i> {% trans "Slider" %}
<h1>{% trans "Sliders" %}</h1>
</div>
{% endblock header %}
{% block dashboard_content %}
{% block search_sliders %}
<div class="table-header">
<h3><i class="icon-search icon-large"></i>{% trans "Buscar sliders" %}</h3>
</div>
<div class="well">
<form action="." method="get" class="form-inline">
{% comment %}
Add the current query string to the search form so that the
sort order is not reset when searching.
{% endcomment %}
{% for name, value in request.GET.items %}
{% if name not in form.fields %}
<input type="hidden" name="{{ name }}" value="{{ value }}"/>
{% endif %}
{% endfor %}
{% include "oscar/dashboard/partials/form.html" with form=form %}
<button type="submit" class="btn btn-primary" data-loading-text="{% trans 'Buscando...' %}">{% trans "Buscar" %}</button>
</form>
</div>
{% endblock %}
{% if sliders %}
{% block slider_list %}
<form action="." method="post">
{% csrf_token %}
{% render_table sliders %}
</form>
{% endblock slider_list %}
{% else %}
<p>{% trans "No hay sliders." %}</p>
{% endif %}
{% endblock dashboard_content %}
EDIT:
per request here's the full traceback and models file
models.py:
class Slider(models.Model):
name = models.CharField(max_length=10, unique=True, verbose_name=_('Nombre'))
tables.py:
class SliderTable(DashboardTable):
actions = TemplateColumn(
verbose_name=_('Acciones'),
template_name='oscar/dashboard/utiles_dashboard/slider_row_actions.html',
orderable=False)
icon = "sitemap"
class Meta(DashboardTable.Meta):
model = Slider
exclude = ('id',)
FULL TRACEBACK:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/store/dashboard/utiles_dashboard/sliders/?sort=name
Django Version: 2.2
Python Version: 3.9.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.flatpages',
'widget_tweaks',
'storages',
'django_extensions',
'background_task',
'rest_framework',
'django_tables2',
'haystack',
'treebeard',
'sorl.thumbnail',
'oscar.config.Shop',
'utiles_oscar.address.apps.AddressConfig',
'oscar.apps.analytics.apps.AnalyticsConfig',
'utiles_oscar.checkout.apps.CheckoutConfig',
'utiles_oscar.shipping.apps.ShippingConfig',
'utiles_oscar.catalogue.apps.CatalogueConfig',
'oscar.apps.catalogue.reviews.apps.CatalogueReviewsConfig',
'utiles_oscar.partner',
'utiles_oscar.basket',
'utiles_oscar.payment',
'oscar.apps.offer.apps.OfferConfig',
'utiles_oscar.order',
'utiles_oscar.customer',
'utiles_oscar.search',
'oscar.apps.voucher.apps.VoucherConfig',
'oscar.apps.wishlists.apps.WishlistsConfig',
'utiles_oscar.dashboard.apps.OscarDashboardConfig',
'utiles_oscar.dashboard.reports.apps.ReportsDashboardConfig',
'oscar.apps.dashboard.users.apps.UsersDashboardConfig',
'utiles_oscar.dashboard.orders.apps.OrdersDashboardConfig',
'utiles_oscar.dashboard.catalogue.apps.CatalogueDashboardConfig',
'oscar.apps.dashboard.offers.apps.OffersDashboardConfig',
'utiles_oscar.dashboard.partners.apps.PartnersDashboardConfig',
'oscar.apps.dashboard.pages.apps.PagesDashboardConfig',
'oscar.apps.dashboard.ranges.apps.RangesDashboardConfig',
'oscar.apps.dashboard.reviews.apps.ReviewsDashboardConfig',
'oscar.apps.dashboard.vouchers.apps.VouchersDashboardConfig',
'oscar.apps.dashboard.communications.apps.CommunicationsDashboardConfig',
'oscar.apps.dashboard.shipping.apps.ShippingDashboardConfig',
'utiles_oscar.dashboard.suppliers.apps.SuppliersConfig',
'utiles_oscar.dashboard.company.apps.CompanyDashboardConfig',
'utiles_oscar.dashboard.utiles_dashboard.apps.UtilesDashboardConfig',
'oscar_promotions.apps.PromotionsConfig',
'oscar_promotions.dashboard.apps.PromotionsDashboardConfig',
'utiles.apps.UtilesConfig']
Installed Middleware:
('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',
'django.middleware.security.SecurityMiddleware',
'utiles.middleware.country_middleware',
'oscar.apps.basket.middleware.BasketMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware')
Template error:
In template C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django_tables2\templates\django_tables2\table.html, error at line 24
Cannot resolve keyword 'name' into field. Choices are: id, image, order, slider, slider_id
14 : {% else %}
15 : <th {{ column.attrs.th.as_html }}>{{ column.header }}</th>
16 : {% endif %}
17 : {% endfor %}
18 : </tr>
19 : </thead>
20 : {% endif %}
21 : {% endblock table.thead %}
22 : {% block table.tbody %}
23 : <tbody>
24 : {% for row in table.paginated_rows %}
25 : {% block table.tbody.row %}
26 : <tr {{ row.attrs.as_html }}>
27 : {% for column, cell in row.items %}
28 : <td {{ column.attrs.td.as_html }}>{% if column.localize == None %}{{ cell }}{% else %}{% if column.localize %}{{ cell|localize }}{% else %}{{ cell|unlocalize }}{% endif %}{% endif %}</td>
29 : {% endfor %}
30 : </tr>
31 : {% endblock table.tbody.row %}
32 : {% empty %}
33 : {% if table.empty_text %}
34 : {% block table.tbody.empty_text %}
Traceback:
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
145. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
143. response = response.render()
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\response.py" in render
106. self.content = self.rendered_content
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\response.py" in rendered_content
83. content = template.render(context, self._request)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\backends\django.py" in render
61. return self.template.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
171. return self._render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in _render
163. return self.nodelist.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\loader_tags.py" in render
150. return compiled_parent._render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in _render
163. return self.nodelist.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\loader_tags.py" in render
150. return compiled_parent._render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in _render
163. return self.nodelist.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\loader_tags.py" in render
150. return compiled_parent._render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in _render
163. return self.nodelist.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\loader_tags.py" in render
62. result = block.nodelist.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\loader_tags.py" in render
62. result = block.nodelist.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\loader_tags.py" in render
62. result = block.nodelist.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\defaulttags.py" in render
309. return nodelist.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\loader_tags.py" in render
62. result = block.nodelist.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django_tables2\templatetags\django_tables2.py" in render
169. return template.render(context={'table': table}, request=request)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\backends\django.py" in render
61. return self.template.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
171. return self._render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in _render
163. return self.nodelist.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\loader_tags.py" in render
150. return compiled_parent._render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in _render
163. return self.nodelist.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\loader_tags.py" in render
62. result = block.nodelist.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\loader_tags.py" in render
62. result = block.nodelist.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\template\defaulttags.py" in render
166. len_values = len(values)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django_tables2\rows.py" in __len__
341. length = len(self.data)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\db\models\query.py" in __len__
256. self._fetch_all()
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\db\models\query.py" in _fetch_all
1242. self._result_cache = list(self._iterable_class(self))
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\db\models\query.py" in __iter__
55. results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
1084. sql, params = self.as_sql()
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\db\models\sql\compiler.py" in as_sql
471. extra_select, order_by, group_by = self.pre_sql_setup()
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\db\models\sql\compiler.py" in pre_sql_setup
54. order_by = self.get_order_by()
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\db\models\sql\compiler.py" in get_order_by
327. order_by.extend(self.find_ordering_name(
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\db\models\sql\compiler.py" in find_ordering_name
701. field, targets, alias, joins, path, opts, transform_function = self._setup_joins(pieces, opts, alias)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\db\models\sql\compiler.py" in _setup_joins
731. field, targets, opts, joins, path, transform_function = self.query.setup_joins(pieces, opts, alias)
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\db\models\sql\query.py" in setup_joins
1503. path, final_field, targets, rest = self.names_to_path(
File "C:\Users\Didier\Desktop\Dionicio\ue-python\venv\lib\site-packages\django\db\models\sql\query.py" in names_to_path
1419. raise FieldError("Cannot resolve keyword '%s' into field. "
Exception Type: FieldError at /store/dashboard/utiles_dashboard/sliders/
Exception Value: Cannot resolve keyword 'name' into field. Choices are: id, image, order, slider, slider_id
I think model doesn't have field name.

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

Problem with initiating form fields as instance variables in form classes

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

Resources