Не удается преобразовать ключевое слово "имя" в поле. Варианты:

Я пытаюсь отфильтровать модель, но каждый раз, когда я пытаюсь, эта ошибка повторяется:

Тип исключения: FieldError в /store/dashboard/utiles_dashboard/sliders/ Значение исключения: Не удается преобразовать ключевое слово «имя» в поле. Возможные варианты: id, изображение, порядок, слайдер, slider_id.

вот часть кода:

просмотров.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

Формы.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

слайдер_список.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>
            <a href="{% url 'dashboard:index' %}">{% trans "Dashboard" %}</a>
        </li>
        <li class="active">{% trans "Sliders" %}</li>
    </ul>
{% endblock %}

{% block header %}
    <div class="page-header action">
        <a href="{% url 'dashboard:utiles_dashboard:slider-create' %}" class="btn btn-primary btn-lg pull-right"><i class="icon-plus"></i> {% trans "Slider" %}</a>
        <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 %}

РЕДАКТИРОВАТЬ:

по запросу здесь полный файл трассировки и моделей

модели.ру:


class Slider(models.Model):
    name = models.CharField(max_length=10, unique=True, verbose_name=_('Nombre'))


таблицы.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',)

ПОЛНЫЙ ОТСЛЕЖ:

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


person Alex    schedule 06.07.2021    source источник
comment
Можете ли вы обновить вопрос с полной трассировкой стека? FieldError возникает при возникновении проблемы с полем модели (документы), поэтому я предполагаю: в вашей SliderSearchForm есть поле name, а в вашей Slider модели нет. Вам нужно обновить вызов filter() в views.py или добавить в модель поле с именем name.   -  person Bjorn    schedule 06.07.2021
comment
Вам нужно предоставить models.py   -  person Siva Sankar    schedule 06.07.2021
comment
Здравствуйте, я только что предоставил класс модели слайдера и полную трассировку.   -  person Alex    schedule 06.07.2021
comment
Основываясь на полной трассировке, есть ли в вашем классе SliderTable также поле name? Не знаком с django_tables2, но кажется, что ошибка возникает, когда django рендерит таблицу.   -  person Bjorn    schedule 06.07.2021
comment
Ну, у него нет поля, но он использует модель Slider, я не очень знаком с django_tables2, так как я имею дело со старым кодом, и эта конкретная часть была сделана другим человеком, которого здесь больше нет, я буду добавьте также код SliderTable для большей ясности.   -  person Alex    schedule 06.07.2021


Ответы (1)


Я думаю, что в модели нет поля name.

person Siva Sankar    schedule 06.07.2021
comment
Это интересная часть, в которой есть поле name - person Alex; 06.07.2021
comment
Это может помочь: stackoverflow.com/a/30590557/11282077 - person Siva Sankar; 06.07.2021