save() method does not save form data to the database (Django ModelForm)

Viewed 681

I'm making a simple todo list using Django, it works fine except that whatever data is entered into the form does not save to the database (and does not get displayed).

My models.py:

    from django.db import models

    class TodoListItem(models.Model):
        content = models.TextField()

        def __str__(self):
            return self.content

forms.py:

from .models import TodoListItem
from django.forms import ModelForm

class TodoListForm(forms.ModelForm):
    class Meta:
        model = TodoListItem
        fields = ['content']

views.py:

from django import forms
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from .models import TodoListItem
from .forms import TodoListForm

def home(request):
    context = {
        'items': TodoListItem.objects.all()
    }
    return render(request, 'home.html', context)

def enter_task(request):
    if request.method == 'POST':
        form = TodoListForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
        else:
            return HttpResponse('Form not valid')
    else:
        form = TodoListForm()
    return render(request, 'form.html', {'form': form})

I did it according to the documentation, what I fail to understand is why the line form.save() won't execute when return HttpResponseRedirect('/') right underneath it does.

The form.html file, just in case:

<!DOCTYPE html>
<html>
    <head>
        <title>Add task</title>
        <h1>Add Task</h1>
    </head>
    <body>
        <form action="{% url 'home' %}" method="post">
            {% csrf_token %}
            {{ form }}
            <input type="submit" value="Submit">
        </form>
    </body>
</html>

I know that the error has to be in views.py because I used the admin site to add to TodoListItem manually and the html file does display it perfectly fine, just that whenever I submit the form it never saves to the aforementioned model.

2 Answers

It is happening that you have entered the form action incorrectly

<form action="{% url 'home' %}" method="post">
   {% csrf_token %}
   {{ form }}
 <input type="submit" value="Submit">
</form>

you have to put this url inside your form action enter_task

        <form action="{% url 'enter_task' %}" method="post">
            {% csrf_token %}
            {{ form }}
            <input type="submit" value="Submit">
        </form>

It looks like your form action is sending the form to your homepage rather than the URL that points to the enter_task view. I don't know this for sure without seeing your urls.py but that's what I'd check.

Related