Reputation: 1479
So, Im trying to save a todo to a database with django. My template is as follows:
<form action="{% url 'todo:add' %}" method="POST">
{% csrf_token %}
<input type="text" id="text" value="{{new_todo_text}}"/>
<input type="submit" value="Submit todo" />
</form>
{%if not_done_todos %}
<ul>
{%for todo in not_done_todos%}
<li>
<span>{{todo.text}}</span>
</li>
{%endfor%}
</ul>
{%else%}
<span>No todos for you!</span>
{%endif%}
My view where Im trying to catch the "new_todo_text" looks like this:
def add(request):
"""Add todo to database"""
new_todo = Todo(text=request.POST.get('new_todo_text'),
done=False, date_created=timezone.now())
new_todo.save()
return HttpResponseRedirect(reverse('todo:index'))
The problem is that the todo.text turns up empty no matter what I add to the form... whats my problem here?
Upvotes: 0
Views: 31
Reputation: 12086
The problem is that inside your input
element you have not declared a name
attribute. That name
attibute will be used as a key to fetch it with Django request.POST
.
So, change to this:
<input type="text" id="text" name="new_todo_text" value="{{new_todo_text}}"/>
The request.POST
dict-like will use the input
's name
and value
to build the dict. Then you can do stuff like request.POST['input_name_here']
.
Upvotes: 2