开发者

form.save() not saving

开发者 https://www.devze.com 2023-03-11 10:54 出处:网络
For some reason, I can\'t get form.save() to save to my database.I\'m able to create the form, and have the form pass itself off to my template, but nothing is getting saved to the database.I\'ve muck

For some reason, I can't get form.save() to save to my database. I'm able to create the form, and have the form pass itself off to my template, but nothing is getting saved to the database. I've mucked around with it for many hours and haven't been able to get it to work.

Any help is appreciated.

Here is the relevant code..

This is my add/model.py

from django.db import models
from django.forms import ModelForm

class addTask(models.Model):
    task = models.CharField('Task',  max_length=60)
    taskNotes = models.CharField('Notes', max_length=600)

    def __unicode__(self):
        return self.task

class addTaskForm(ModelForm):
    class Meta:
        model = addTask

template/addTHEtask.html. This is getting referenced correctly.

    <form action="/todo/" method="post">
    {{ form.as_p }开发者_Python百科}
    <input type="submit" value="Add Task" />
    </form>

add/views.py

from django.shortcuts import render_to_response
from django.template import RequestContext
from myToDo.add.models import addTask, addTaskForm

def create_task(request):
    if request.method == 'POST':
        form = addTaskForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = addTaskForm()
    return render_to_response('addTHEtask.html', {'form': form})


To properly debug your code, change your template to:

<form action="/todo/" method="post"> {{ csrf_token }}
    {{ form.errors }}
    {{ form.as_p }}
    <input type="submit" value="Add Task" />
</form>

And your view to:

def create_task(request):
    if request.method == 'POST':
        form = addTaskForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = addTaskForm()
    return render_to_response(
                     'addTHEtask.html', 
                     {'form': form}, 
                     context_instance=RequestContext(request))

I don't think the context_instance will do anything significant for you, but it is usually the right thing to pass when using render_to_response.

Showing the errors in the form may help you track down what the actual problem is. Your code looks (mostly) correct, except the missing csrf_token. Adding the token, and displaying any errors, should show you what is going wrong.

0

精彩评论

暂无评论...
验证码 换一张
取 消