繁体   English   中英

Django 输入 forms 没有出现在我的模板中

[英]Django input forms not showing up in my template

我的问题是,当我将 go 添加到我的 add.html 页面时,标题和文本区域的输入 forms 没有显示。 对于上下文,这是一个在线课程,我必须在其中设计一个“wiki”。 这部分代码用于添加条目(标题和正文内容)

这是我的代码:

视图.py

class Form(forms.Form):
    title = forms.CharField(label="Post Title")
    textarea = forms.CharField(widget=forms.Textarea(), label='')

def create(request):
    if request.method == "POST":
        form = Form(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")
            else:
                util.save_entry(title, textarea)
                page = util.get_entry(title)
                page_converted = markdowner.convert(page)

                context = dict(body=page_converted, title=title)

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

地址:html

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

{% block body %}
<h1>
    Add Post
</h1>
    <form action="{% url 'create' %}" method="post">
        {% csrf_token %}
        <h6 class="post-title">Title: {{ post.title }}</h6>
            {{ post.textarea }}
        <input type="submit" value="add entry">
    </form>
    <a href="{% url 'index' %}">View Entries</a>
{% endblock %}

尝试使用这个:-

地址:html

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

 {% block body %}

<h2>Add Post</h2>
<div class="container">
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <table>
        {{ form.as_p }}
        </table>
        <button type="submit">Add</button>
    </form>
</div>
<a href="{% url 'index' %}">View Entries</a>

{% endblock body %}

视图.py

def create(request):

    if request.method != 'POST':

        form = Form()
    else:

        form = Form(data=request.POST)
        new_post = form.save(commit=False)
        new_post.owner = request.user
        new_post.save()
        return redirect('/') #put here, whatever and whenever you want to redirect.


    context = {'form':form}
    return render(request, 'mains/create.html', context)

使用 Django forms 或 bootstrap|html forms 请不要尝试同时包含两者。 这里的问题是你不应该使用

{{post.title}} -> {{post}} and remove {{post.textarea}}

有关更多信息,请参阅此处

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM