表单未显示在页面中

2024-04-26 05:35:33 发布

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

嘿,伙计们需要一点帮助,我好像想不出来。由于某些原因,我的表单不会显示在我的页面中,请参阅下面的代码

forms.py

class NewEntryForm(forms.Form):
    title = forms.CharField(label = "Title")
    content = forms.CharField(label = "Body")

views.py

def new(request):
    if request.method == 'POST':
        form = NewEntryForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data['title']
            content = form.cleaned_data['body']
            content = markdown2.markdown(title)
            filename = f"entries/{title}.md"
            if default_storage.exists(filename):
                return render(request, "encyclopedia/error.html", {
                    "error":'A file with this title already exists.'
                })
            else:
                util.save_entry(title, content)
                return redirect('entry_page', title=title)
    else:
        return render(request, 'encyclopedia/new.html', {'form':NewEntryForm()})

url.py

urlpatterns = [
    path("", views.index, name="index"),
    path("wiki/<str:title>", views.entry, name="entry"),
    path("search/", views.search, name="search"),
    path("wiki/new", views.new, name="new")
]

new.html

{% extends "encyclopedia/layout.html" %}

{% block title %}
  Encyclopedia
{% endblock %}

{% block body %}
  <form class="" action="" method="post">
    {% csrf_token %}
    {{form}}
    <input type="submit" name="" value="Submit">

  </form>
{% endblock %}

Page output

cli output


2条回答

你能试试吗

def new(request):
    if request.method == 'POST':
        form = NewEntryForm(request.POST)
        if form.is_valid():
            # ...
    else:
        form = NewEntryForm()
        
    return render(request, 'encyclopedia/new.html', {'form': form})

从逻辑上讲,您在这部分中遗漏了什么(在默认存储内容中)

return render(request, "encyclopedia/error.html", {
    "error": 'A file with this title already exists.'
})

是您渲染了错误,但未包含实际表单。从技术上讲,您也可以像下面的示例那样修复它,但我更愿意按照documentation给我们的方式进行修复

return render(request, "encyclopedia/error.html", {
    "error": 'A file with this title already exists.',
    "form": form    # you didn't include your form in the inner return
})

原来是我的URL.py文件。接受str参数的url正在验证为空白页,因为Django按顺序检查url。我只是将str url移到了urls.py的底部,它成功了

相关问题 更多 >