表单出现错误“预期的表或查询集,而不是 str”

Posted

技术标签:

【中文标题】表单出现错误“预期的表或查询集,而不是 str”【英文标题】:Error "Expected table or queryset, not str " for form 【发布时间】:2020-10-25 14:59:45 【问题描述】:

我正在使用 python django 构建一个用于库存管理的私人网站,并且我正在创建一个表单以在我的 Item 模型中添加项目,直到现在我已经重做了我的表单代码 2-3 次,但是我总是遇到同样的错误“预期的表或查询集,而不是 str”并且已经没有想法了。 这是我的代码,

views.py:

from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from .models import Item, Tender
from django.urls import reverse
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
from .forms import NewUserForm, AddItemForm
from .tables import ItemTable


def item_list(request):
    table = ItemTable(Item.objects.all())

    return render(request, "main/item_list.html", 
        "table": table
    )

def add_item(request):
if request.method == 'POST':
    form = AddItemForm(request.POST)
    if form.is_valid():
        Item = form.save(commit = False)
        Item.item_updated = timezone.now()
        Item.save()
        return redirect("main:item_list")

else:
    form = AddItemForm()


return render(request, "main/item_list.html", 'form': form)

models.py:

from django.db import models
from datetime import datetime
from django.contrib.auth.models import User

class Item(models.Model):
    item_no = models.CharField(max_length=200, primary_key = True )
    item_name = models.CharField(max_length = 200)
    item_quantity = models.CharField(max_length = 200, default = 0)
    item_description = models.TextField(blank = True)
    item_updated = models.DateTimeField("Item updated", default=datetime.now())
    item_price = models.CharField(max_length = 100, default = 0)

    def __str__(self):
        return self.item_name

forms.py:

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from .models import Item
from datetime import datetime

class AddItemForm(forms.ModelForm):

    class Meta:
        model = Item
        fields = (
            'item_no', 'item_name', 'item_quantity', 'item_description', 'item_price'
        )

add_item.html:

% extends "main/header.html" %

    % block content %
        <h1>Add Item Form</h1>

        <form method="POST" class="post-form">
            % csrf_token %
            form.as_p
            <button class="btn" type="submit">Add Item</button>
        </form>

    % endblock %

urls.py:

from django.urls import path
from . import views

app_name = "main"

urlpatterns = [
    path("", views.homepage, name="homepage"),
    path("register/", views.register, name="register"),
    path("logout/", views.logout_request, name="logout"),
    path("login/", views.login_request, name="login"),
    path("item_list/", views.item_list, name="items"),
    path("tender/", views.tender, name="tender"),
    path("add_item/", views.add_item, name="add_item"),


]

tables.py:

import django_tables2 as tables
from .models import Item

class ItemTable(tables.Table):
    class Meta:
        model = Item

item_list.html:

% extends "main/header.html" %
% load render_table from django_tables2 %

  % block content %
    <a href = "/add_item" class="waves-effect waves-light btn"><i class="material-icons left">add_circle</i>Add Item</a>
    % render_table table %

  % endblock %

堆栈跟踪:

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\core\handlers\exception.py” 在内部 34. response = get_response(request)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\core\handlers\base.py” 在 _get_response 126. response = self.process_exception_by_middleware(e, request)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\core\handlers\base.py” 在 _get_response 124. response = Wrapped_callback(request, *callback_args, **callback_kwargs)

add_item 中的文件“C:\Users\ASUS\mysite\main\views.py” 88. return render(request, "main/item_list.html", 'form': form)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\shortcuts.py” 在渲染中 36. content = loader.render_to_string(template_name, context, request, using=using)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\template\loader.py” 在 render_to_string 62. return template.render(context, request)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\template\backends\django.py” 在渲染中 61. return self.template.render(context)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\template\base.py” 在渲染中 171. 返回 self._render(context)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\template\base.py” 在_render 163. return self.nodelist.render(context)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\template\base.py” 在渲染中 937. bit = node.render_annotated(context)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\template\base.py” 在 render_annotated 904. return self.render(context)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\template\loader_tags.py” 在渲染中 150. 返回已编译的_parent._render(context)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\template\base.py” 在_render 163. return self.nodelist.render(context)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\template\base.py” 在渲染中 937. bit = node.render_annotated(context)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\template\base.py” 在 render_annotated 904. return self.render(context)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\template\loader_tags.py” 在渲染中 62. 结果 = block.nodelist.render(context)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\template\base.py” 在渲染中 937. bit = node.render_annotated(context)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django\template\base.py” 在 render_annotated 904. return self.render(context)

文件 “c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django_tables2\templatetags\django_tables2.py” 在渲染中 145. raise ValueError("Expected table or queryset, not ".format(klass))

异常类型:ValueError at /add_item/ 异常值:预期 表或查询集,而不是 str

任何帮助将不胜感激

【问题讨论】:

你能分享你的完整堆栈跟踪吗? 这个错误很可能是由于 django-tables 包造成的。尝试将 django-tables 更新到此处提到的最新版本:***.com/questions/29683290/… 我检查了我的 django-tables 是最新的 【参考方案1】:

当您尝试渲染“item_list.html”时,您的错误似乎正在发生。

File "C:\Users\ASUS\mysite\main\views.py" in add_item 88. return render(request, "main/item_list.html", 'form': form)

这是您似乎没有提供的一个文件:)

顺便说一句,问题在于您如何使用 django_tables2 库。我不熟悉 django_tables2,但从堆栈跟踪的那部分开始

File "c:\users\asus\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages\django_tables2\templatetags\django_tables2.py" in render 145. raise ValueError("Expected table or queryset, not ".format(klass))

您似乎正在将一个字符串传递给某个“需要一个表或查询集”的标签

【讨论】:

我已经添加了item_list.html代码,我查看了但是没有找到问题。 天哪,这看起来与文档相符。我不确定我能否提供更多帮助。

以上是关于表单出现错误“预期的表或查询集,而不是 str”的主要内容,如果未能解决你的问题,请参考以下文章

Django 重复键值违反唯一约束错误模型表单

Web前端开发,有八个错误点你必须注意

为啥我应该没有错时却出现链接错误

Laravel用post提交表单常见的两个错误

为啥即使没有错误,表单也会出现错误消息?

出现错误“由于表单未连接而取消表单提交”