使用django forms.py获取用户输入什么都不返回

时间:2018-04-25 09:08:08

标签: python html django

我试图获取用户输入并添加到数据库中的表中,一切顺利,没有错误..但输入未添加到数据库

urls.py

path('category/add/', views.add_cat, name="add_cat"),

view.py

def add_cat(request):
        # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = CatForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            entry = Categories.objects.create(category_name=new_cat_name)
            entry.save()
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = CatForm()

    return render(request, 'add_cat.html', {'form': form})

add_cat.html

{% extends 'base.html' %}
    {% block content %}
{% load static %}
<form action="/" method="post">
    {% csrf_token %}
    {% for form in form %}
    <h3 align="center">{{ form.label }}</h3>
    <div align="center">{{ form }}</div>
    <br>
    <br>
    {% endfor %}
    <div align="center">
    <input type="submit" class="btn btn-dark" style="width: 100px;"value="إضافة" />
</div>
</form>
{% endblock %}

1 个答案:

答案 0 :(得分:1)

{% extends 'base.html' %}
    {% block content %}
{% load static %}
<form action="" method="post">
    {% csrf_token %}
    {% for form in form %}
    <h3 align="center">{{ form.label }}</h3>
    <div align="center">{{ form }}</div>
    <br>
    <br>
    {% endfor %}
    <div align="center">
    <input type="submit" class="btn btn-dark" style="width: 100px;"value="إضافة" />
</div>
</form>
{% endblock %}

更改您的表单操作,您将数据发布到&#39; /&#39;网址但您需要将其添加到添加视图中

if form.is_valid():
        form.save()
        return HttpResponseRedirect('/')