Cannot resolve keyword 'name' into field. Choices are: - python-3.x

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.

Related

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.

Django 3.1.3 Field 'id' expected a number but got '{{ \r\nchoice.id }}'

I'm stuck at Django's official tutorial (see Writing your first Django app, part 4).
https://docs.djangoproject.com/en/3.1/intro/tutorial04/
I get the following error:
https://i.stack.imgur.com/7zPI9.png
In this Django project, inside the poll app I'm making, we're supposed to make a vote() view in views.py which should process the POST request data of the poll and redirect us to the results() view (there's no template for the vote()view, it's just in charge of processing the data we send through the poll). At first I thought I had a typo error, but I then copy-pasted everything directly out of the documentation tutorial (which I linked at the beginning of this question) and the error persisted.
views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.http import Http404
from django.shortcuts import get_object_or_404, render
from django.template import loader
from django.urls import reverse
from .models import Choice, Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
urls.py
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
Results.html
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{
choice.votes|pluralize }}
</li>
{% endfor %}
</ul>
Vote again?
Index.html
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{
question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Detail.html
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
<input type="submit" value="Vote">
</form>
If this helps anyone
Traceback (most recent call last):
File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Danny\Python\Poll\mysite\polls\views.py", line 41, in vote
selected_choice = question.choice_set.get(pk=request.POST['choice'])
File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 418, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line
1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line
1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line
1319, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line
1165, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\lookups.py", line 76, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1776, in get_prep_value
raise e.__class__(
ValueError: Field 'id' expected a number but got '{{ \r\nchoice.id }}'.
for some reason django is redirecting with the int: question_id as string, could you add your urls file?
I got the same error when I learned the tutorial part 4.
Error: Field 'id' expected a number but got '{{ \r\nchoice.id }}'
the error is "\r\n" before the choice.id
In detail.html, there should be no carriage return here.
value="{{ choice.id }}"
Remove the carriage return before choice.id, then refresh the web page. Shouldn't be an error.
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
<input type="submit" value="Vote">
</form>

django-filter not filtering the query

I applied django-filter library in my project if it's not filtering the items.
if i visit the url http://127.0.0.1:8000/products/?q=&category=electronics it should gives the only electronics products but its giving the all available products. What i am doing wrong? it should filter categories wise or product title wiase and price wise.
class ProductFilter(FilterSet): # by using django-filters
title = CharFilter(field_name='title', lookup_expr='icontains', distinct=True)
category = CharFilter(field_name='categories__title', lookup_expr='icontains', distinct=True)
category_id = CharFilter(field_name='categories__id', lookup_expr='icontains', distinct=True)
min_price = NumberFilter(field_name='price', lookup_expr='gte', distinct=True)
max_price = NumberFilter(field_name='price', lookup_expr='lte', distinct=True)
class Meta:
model = Product
fields = ['category', 'title', 'description', 'min_price', 'max_price']
class FilterMixin(object):
filter_class = ProductFilter
search_ordering_param = 'ordering'
def get_queryset(self, *args, **kwargs):
try:
qs = super(FilterMixin, self).get_queryset(*args, **kwargs)
return qs
except:
raise ImproperlyConfigured("You must have a queryset in order to use the FilterMixin")
def get_context_data(self, *args, **kwargs):
context = super(FilterMixin, self).get_context_data(*args, **kwargs)
qs = self.get_queryset()
ordering = self.request.GET.get(self.search_ordering_param)
if ordering:
qs = qs.order_by(ordering)
filter_class = self.filter_class
print(filter_class)
if filter_class:
f = filter_class(self.request.GET, queryset=qs)
context['object_list'] = f
return context
class ProductListView(FilterMixin, ListView):
queryset = Product.objects.all()
filter_class = ProductFilter
def get_context_data(self, *args, **kwargs):
context = super(ProductListView, self).get_context_data(*args, **kwargs)
context['filter_form'] = ProductFilterForm(data=self.request.GET or None)
return context
Template File-
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<div class='col-sm-2'>
<form method="GET" action="{% url 'products:product-list' %}">
{{ filter_form|crispy }}
<input type='hidden' name='q' value='{{ request.GET.q }}' />
<input type='submit' value='Apply Filter' class='btn btn-default'>
</form>
Clear Filters
</div>
<div class='col-sm-12'>
<h3>All Products <small>*Categories*</small></h3>
{% if product_list %}
<div class="row">
{% for product in product_list %}
<div class="col">
{% include 'products/snippets/card.html' with instance=product %}
</div>
{% endfor %}
{% else %}
<p>No product found!!</p>
{% endif %}
</div>
</div>
{% endblock %}
Your FilterMixin never exports something like a product_list, so that will be the original queryset, not the one that you filter with the FilterSet.
You can easily update this with:
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
qs = context['object_list']
if self.filter_class:
qs = self.filter_class(self.request.GET, queryset=qs).qs
ordering = self.request.GET.get(self.search_ordering_param)
if ordering:
qs = qs.order_by(ordering)
context['object_list'] = qs
context_object_name = self.get_context_object_name(qs)
if context_object_name is not None:
context[context_object_name] = qs
return context

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

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

Sending multiple instance forms to template - Django

Hi Stack overflow people:
I would lithe to receive some orientation in this following newbie python Error
I have two model forms in my forms.py:
class StrategicDnaValuePropositionForm(forms.ModelForm):
title = "Adn Estratégico y Propuesta de valor"
class Meta:
widgets = {
'familiar_enterprise':forms.RadioSelect,
'enterprise_concepts':forms.RadioSelect,
'value_purpose_target':forms.RadioSelect,
'competition_differentiation':forms.RadioSelect,
'goals_objectives':forms.RadioSelect,
'avoid_competition':forms.RadioSelect,
'enterprise_strategy':forms.RadioSelect,
}
model = StrategicDnaValueProposition
fields = ('familiar_enterprise', 'enterprise_size',
'enterprise_concepts', 'value_purpose_target', 'competition_differentiation', 'goals_objectives',
'avoid_competition')
class MarketingSalesForm(forms.ModelForm):
title = "Mercadeo y Ventas"
class Meta:
widgets = {
'key_activities':forms.RadioSelect,
'new_clients_strategies':forms.RadioSelect,
}
model = MarketingSales
fields = ('key_activities', 'new_clients_strategies',)
In my view, I would like to generate two forms instances of these model forms and send to the template to save them.
My views.py:
#login_required
def diagnostic_tool_questions(request):
user = request.user
# Populate the forms
form_diagnostic = []
if user.is_enterprise:
profile = user.get_enterprise_profile()
form_diagnostic.append({
'form_strategicdna': StrategicDnaValuePropositionForm,
'form_marketing_sales': MarketingSalesForm,
'instance': user.enterpriseprofile,
})
if request.method == 'POST':
# forms = [x['form'](data=request.POST,) for x in form_diagnostic]
forms = [x['form'](data=request.POST, instance=x['instance'],) for x in form_diagnostic]
if all([form.is_valid() for form in forms]):
for form in forms:
form.save()
return redirect('dashboard')
else:
forms = [x['form'](instance=x['instance']) for x in form_diagnostic]
return render(
request, 'enterprise_process/strategicdnavalueproposition_form.html',
{'forms':forms, 'userprofile':profile,})
My template is:
{% extends 'layout.html' %}
{% load bootstrap3 %}
{% block title_tag %}Herramienta de Diagnóstico | CRIMBLU {{ block.super }}{% endblock %}
{% block body_content %}
<div class="container">
<h1>Account Details</h1>
<form method="POST">
{% csrf_token %}
{% for form in forms %}
{% bootstrap_form form %}
{% endfor %}
<input type="submit" value="Save Changes" class="btn btn-default">
</form>
</div>
{% endblock %}
When I go to the url which call to my diagnostic_tool_questions view I get the following message:
System check identified no issues (0 silenced).
May 26, 2017 - 19:40:20
Django version 1.11, using settings 'consultancy.settings.development'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /herramienta-diagnostico/preguntas/
Traceback (most recent call last):
File "/home/bgarcial/.virtualenvs/consultancy_dev/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/bgarcial/.virtualenvs/consultancy_dev/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/bgarcial/.virtualenvs/consultancy_dev/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/bgarcial/.virtualenvs/consultancy_dev/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/bgarcial/workspace/consultancy_project/enterprise_process/views.py", line 66, in diagnostic_tool_questions
forms = [x['form'](instance=x['instance']) for x in form_diagnostic]
File "/home/bgarcial/workspace/consultancy_project/enterprise_process/views.py", line 66, in <listcomp>
forms = [x['form'](instance=x['instance']) for x in form_diagnostic]
KeyError: 'form'
[26/May/2017 19:40:23] "GET /herramienta-diagnostico/preguntas/ HTTP/1.1" 500 89072
Django tell me that I have some interprete error in the line:
else:
forms = [x['form'](instance=x['instance']) for x in form_diagnostic]
The KeyError: 'form' I unknown the reason which appear ...
Excuse me by the newbie error.

Resources