【问题标题】:Why is my forms content showing in the title for my edit function? Django为什么我的表单内容显示在我的编辑功能的标题中?姜戈
【发布时间】:2021-12-30 11:06:33
【问题描述】:

我目前正在执行一项任务,其中对编辑功能的要求之一是用户应该能够单击编辑按钮并被带到他们可以选择编辑之前编写的内容的页面。

我遇到的问题是我正在使用 INITIAL 推送以前填充的内容以便它显示,但这会一直显示在页面标题上,而不是在 textarea 内容内。

我曾尝试对此进行调整,但经过多次尝试,我一直遇到相同的问题,当我提交此内容时,它给了我一个新条目/页面,而我想要做的是编辑页面而不是创建新页面.

VIEWS.PY

class AddPageForm(forms.Form):
    title = forms.CharField()
    content = forms.CharField(widget=forms.Textarea(
        attrs={
            "class": "form-control",
        })
    )
    
def edit_page(request, title):
    if request.method == "GET":
        title = title
        content = util.get_entry(title)
        form = AddPageForm({"title": title, "content": content})
        return render(
            request,
            "encyclopedia/editpage.html",
            {"form": form, "title": title}
        )

    form = AddPageForm(request.POST)
    if form.is_valid():
        title = form.cleaned_data.get("title")
        content = form.cleaned_data.get("content")

        util.save_entry(title=title, content=content)
        return redirect('encyclopedia:entrypage', title)

编辑页面

{% block body %}

    <h1>Edit</h1>

    <form action="{% url 'encyclopedia:editpage' title %}" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Submit" class="btn btn-secondary">
    </form>

{% endblock %}

进入页面

{% block body %}
        {{ content|safe }}

        <a href="{% url 'encyclopedia:editpage' 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")

]

【问题讨论】:

    标签: django django-views django-forms cs50


    【解决方案1】:

    在 get_entry 函数中,你得到了对象吗?如是 将您的视图更改为类似的内容

        content = util.get_entry(title)
        form = AddPageForm({"title": title, "content": content.content})
    

    【讨论】:

    • 这给了我这个错误AttributeError at /edit_page/Testing to see if the bug I have had has been corrected 'str' object has no attribute 'content'
    • 你能告诉我你的get_entry函数吗?
    猜你喜欢
    • 2016-06-16
    • 2011-04-12
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多