提交django表格

时间:2018-05-04 14:10:13

标签: django django-forms django-templates django-views

我有django表单的问题,在提交表单时似乎没有任何事情发生,即使服务器没有得到任何响应,除了GET请求查看表单模板。

这是我的forms.py代码:

from django.forms import ModelForm
from .models import Post


class PostForm(ModelForm):
    class Meta:
        model = Post 
        fields = [
            "title",
            "content",
            "category"
        ]

这是我的post_form.html:

{% extends 'base.html' %}


{% block content %}
    <h1>form</h1>
    <form method="POST" action=".">
        {% csrf_token %}
        {{ form.as_p }}
    </form>
    <button type="submit">Create Post</button>
{% endblock content %}

这是我对views.py中的表单的处理:

def post_create(request):

    if request.method == "POST":
        form = PostForm(request.POST)

        if form.is_valid():
            post = form.save(commit=False)
            post.save()

            return redirect("posts:detail", pk=post.pk)
    else :
        form = PostForm()

    context = {
        "form":form,
    }

    return render(request,"post_form.html", context)

1 个答案:

答案 0 :(得分:0)

forms.py

from django.forms import ModelForm
from .models import Post


class PostForm(ModelForm):
    class Meta:
        model = Post 
        fields = ["title", "content", "category"]

views.py

def post_create(request):
    form = PostForm()
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save()
            return redirect("posts:detail", pk=post.pk)
    return render(request,"post-form.html", {"form": form})

-form.html交

{% extends 'base.html' %}
{% block content %}
    <h1>form</h1>
    {% for error in form.non_field_errors %}
         <article class="message is-danger alert-message">
             <div class="message-body">
               <p>{{ error|escape }}</p>
             </div>
         </article>
    {% endfor %}
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Create Post">
    </form>
{% endblock content %}