python - 'str'对象在django中没有属性'get'属性错误
问题描述
这是views.py
class EditForm(forms.Form):
content = forms.CharField(label="content",widget=forms.Textarea,required=True)
def edit(request, title):
if request.method == "POST":
form = EditForm(request.POST)
if form.is_valid():
content = form.cleaned_data["content"]
util.save_entry(title, content)
return render(request, "encyclopedia/page.html", {
"title": title,
"content": util.get_entry(title)
})
else:
content = util.get_entry(title)
return render(request, "encyclopedia/edit.html", {
"form":EditForm(content)
})
这是 urls.py
path("wiki/<str:title>/edit", views.edit, name="edit")
这是 util.py,根据项目,这不是要更改的。
def list_entries():
""" 返回百科全书条目的所有名称列表。"""
_, filenames = default_storage.listdir("entries")
return list(sorted(re.sub(r"\.md$", "", filename)
for filename in filenames if filename.endswith(".md")))
def save_entry(title, content):
""" 保存一个百科全书条目,给定它的标题和 Markdown 内容。如果已经存在具有相同标题的现有条目,则将其替换。"""
filename = f"entries/{title}.md"
if default_storage.exists(filename):
default_storage.delete(filename)
default_storage.save(filename, ContentFile(content))
def get_entry(title):
""" 按标题检索百科全书条目。如果不存在这样的条目,则函数返回 None。"""
try:
f = default_storage.open(f"entries/{title}.md")
return f.read().decode("utf-8")
except FileNotFoundError:
return None
这是edit.html
% extends "encyclopedia/layout.html" %}
{% block title %}
Edit {{ title }}
{% endblock %}
{% block body %}
<form action="/wiki/{{ title }}/edit" method="post">
{% csrf_token %}
{{ form }}
<input type="submit">
</form>
{% endblock %}
这是错误:*
Internal Server Error: /wiki/harsha1/edit
Traceback (most recent call last):
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\harsh\Desktop\wiki\encyclopedia\views.py", line 91, in edit
"form":EditForm(content)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\base.py", line 170, in render
return self._render(context)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\base.py", line 994, in render
return render_value_in_context(output, context)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\template\base.py", line 973, in render_value_in_context
value = str(value)
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\utils\html.py", line 376, in <lambda>
klass.__str__ = lambda self: mark_safe(klass_str(self))
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\forms\forms.py", line 134, in __str__
return self.as_table()
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\forms\forms.py", line 277, in as_table
errors_on_separate_row=False,
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\forms\forms.py", line 195, in _html_output
top_errors = self.non_field_errors().copy()
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\forms\forms.py", line 306, in non_field_errors
return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield'))
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\forms\forms.py", line 172, in errors
self.full_clean()
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\forms\forms.py", line 374, in full_clean
self._clean_fields()
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\forms\forms.py", line 386, in _clean_fields
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "C:\Users\harsh\Anaconda3\lib\site-packages\django\forms\widgets.py", line 258, in value_from_datadict
return data.get(name)
AttributeError: 'str' object has no attribute 'get'
[22/Aug/2020 12:18:10] "GET /wiki/harsha1/edit HTTP/1.1" 500 173523
当我转到 /title/edit 路线时,我得到 'str' 对象没有属性 'get' 属性错误。我是 django 新手,请详细说明,提前致谢。
解决方案
https://docs.djangoproject.com/en/3.1/ref/forms/api/#bound-and-unbound-forms
要将数据绑定到表单,请将数据作为字典作为第一个参数传递给 Form 类构造函数:
在文档中:
表格.py:
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
视图.py
data = {'subject': 'hello',
'message': 'Hi there',
'sender': 'foo@example.com',
'cc_myself': True}
f = ContactForm(data)
在您的代码中,编辑表单:
class EditForm(forms.Form):
content = forms.CharField(label="content",widget=forms.Textarea,required=True)
所以:
content = util.get_entry(title)
return render(request, "encyclopedia/edit.html", {
"form":EditForm({'content',content})
})
推荐阅读
- python - 检测 7 张扑克手牌中的顺子
- powershell - 如何让我的 windows conda 识别安装在 Ubuntu 中的 ANT?
- sleep - 我在使用 sleep 和 fork 将参数传递给 execvp 时遇到问题
- binary-tree - 当存储为节点和引用时,二叉树如何浪费内存?
- javascript - 在 tensorflow js api 0.15.3 中为卷积层设置配置
- python - 在python中使用十六进制进行AES解密?
- python - Django 2.1.7 - 从用户(x)中检索所有模型字段
- php - 遇到错误您尚未选择要连接的数据库类型
- javascript - JavaScript:为什么我会收到这个 AssertionError?
- c# - 如何声明要在多个方法中使用的变量?