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.