簡體   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