Ahmed Wagdi
Ahmed Wagdi

Reputation: 4391

Getting user input using django forms.py return nothing

I'm trying to get the users input and add to a table in the database, everything goes smoothly with no errors .. but the input is not added to DB

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 %}

Upvotes: 0

Views: 43

Answers (1)

Exprator
Exprator

Reputation: 27513

{% 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 %}

change your form action, you were posting the data to '/' url but you need to put it in your add view

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

Upvotes: 1

Related Questions