Django应用程序中的TypeError

2024-04-24 05:22:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在申请Django。这是一个维基百科页面,如果你点击它,你可以创建一个新页面

路径在URL中,模式为:

path("create", views.create, name="create")

views.py中的函数是:

def create(request):
if request.method == 'POST':
    form = Post(request.POST)
    if form.is_valid():
        title = form.cleaned_data["title"]
        textarea = form.cleaned_data["textarea"]
        entries = util.list_entries()
        if title in entries:
            return render(request, "encyclopedia/error.html", {"form": Search(), "message": "Page already exist"})
        else:
            util.save_entry(title,textarea)
            page = util.get_entry(title)
            page_converted = markdowner.convert(page)

            context = {
                'form': Search(),
                'page': page_converted,
                'title': title
            }

            return render(request, "encyclopedia/entry.html", context)
else:
    return render(request, "encyclopedia/create.html", {"form": Search(), "post": Post()})

我收到的错误消息是:

TypeError:解码为str:需要像object这样的字节,未找到类型

完全回溯:

回溯(最近一次呼叫最后一次): 文件“/Users/franciscogutierrez/Desktop/Software1/CS50W/project1/wiki/env/lib/python3.8/site packages/django/core/handlers/exception.py”,第47行,在内部 响应=获取响应(请求) 文件“/Users/franciscogutierrez/Desktop/Software1/CS50W/project1/wiki/env/lib/python3.8/site packages/django/core/handlers/base.py”,第179行,在“获取”响应中 响应=包装的回调(请求,*回调参数,**回调参数) 文件“/Users/franciscogutierrez/Desktop/Software1/CS50W/project1/wiki/encyclopedia/views.py”,第60行,在网页中 “标题”:markdowner.convert(第页) 文件“/Users/franciscogutierrez/Desktop/Software1/CS50W/project1/wiki/env/lib/python3.8/site packages/markdown2.py”,第316行,转换格式 text=unicode(文本“utf-8”) TypeError:解码为str:需要像object这样的字节,未找到类型


Tags: 文件pyformtitlerequestcreatewikipage
2条回答

如跟踪所示,您在markdowner函数中传递None,而它希望您发送字节对象。您正在从utils.get\u输入函数获取页面。确保不返回None。如果不可能,请在调用markdower函数之前检查None值。像这样试试-

page = util.get_entry(title)
if page:
    page_converted = markdowner.convert(page)

有一个str:title路径在“create”路径之前运行,因此create将位于上面的路径而不是另一个路径。通过将create放在str:title的顶部修复了它

相关问题 更多 >