【发布时间】:2021-12-29 10:10:42
【问题描述】:
我试图使现有内容成为文本区域的初始值(即用户在添加该页面之前输入的内容应该在用户想要编辑页面时显示。)当用户点击编辑按钮时.
当我点击编辑时,之前写的内容往往会转到 url 中的标题页。你能帮我看看为什么吗?
VIEWS.PY
class AddPageForm(forms.Form):
title = forms.CharField(max_length=20)
content = forms.CharField(widget=forms.Textarea(
attrs={
"class": "form-control",
})
)
class EditPageForm(forms.Form):
content = forms.CharField(widget=forms.Textarea(
attrs={
"class": "form-control",
})
)
def edit_page(request, title):
entry = util.get_entry(title)
if request.method == "GET":
form = EditPageForm(request.POST, initial={
"content": entry
})
else:
form = EditPageForm(request.POST)
if form.is_valid():
title = form.cleaned_data['title']
content = form.cleaned_data['content']
util.save_entry(title, content)
return redirect('encyclopedia:entrypage', title)
return render(request, 'encyclopedia/editpage.html', {'form': form})
编辑页面
{% block body %}
<h1>Edit {{ title }}</h1>
<form action="" method="post">
{% csrf_token %}
{% form %}
<input type="submit" value="Submit" class="btn btn-secondary">
</form>
进入页面
{% block body %}
{{ content|safe }}
<a href="{% url 'encyclopedia:editpage' title=title %}" class="btn btn-primary">Edit</a>
{% endblock %}
URLS.PY
app_name = "encyclopedia"
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:title>", views.entry_page, name="entrypage"),
path("search", views.search, name="search"),
path("add_page", views.add_page, name="addpage"),
path("edit_page/<str:title>", views.edit_page, name="editpage")
]
【问题讨论】:
-
当
request.method == "GET"不要将request.POST传递给您的表单 -
你好Iain,GET是接收客户之前输入的信息,POST是更新编辑的评论。我也尝试删除 request.POST,我仍然遇到同样的问题
标签: django django-views django-forms cs50