如何使用Django ModelForm将数据提交到数据库?

时间:2013-05-09 10:40:55

标签: python django

我正在学习一些Django,现在我在使用Forms时遇到了困难。我想要做的是创建一个表单,让人们在页面上留下消息,这些消息将显示在同一页面中(就像博客评论系统一样)。我按照文档

创建了一个类和ModelForm
class Recado(models.Model):
    recado = models.TextField()
    data = models.DateTimeField(auto_now_add=True)
    nome = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)

    def __unicode__(self):
        return self.recado

class RecadoForm(ModelForm):
    class Meta:
        model = Recado
        exclude = ('data',)

然后是我的观点:

def index(request):
    RecadoForm = modelform_factory(Recado, exclude=('data'))
    form = RecadoForm()
    lista_recados = Recado.objects.order_by('-data')
    template = loader.get_template('recados/index.html')
    context = Context({'lista_recados': lista_recados,})
    return render_to_response("recados/index.html", { "form": form,}, context_instance=RequestContext(request))

模板:

<div class="conteudo-site conteudo-recados">
    <form method="post" action="salvar_recado">
        {% csrf_token %}            
        {{ form.as_p }}
        <br /><input class="button" type="submit" value="Deixar Recado" />
    </form>
    {% if lista_recados %}
        {% for recado in lista_recados %}
            <p>{{ recado.nome }}</p>
            <p>{{ recado.data }}</p>
            <p>{{ recado.recado }}</p>
            <br />
        {% endfor %}
    {% else %}
        <p>Ainda não existem recados. Deixe o seu :)</p>
    {% endif %}
</div>

这会在页面上正确生成表单,但是当我单击提交按钮时,它不会将数据保存在数据库中,现在我无法弄清楚要做什么。用观点尝试了一些事情,但没有任何效果。

有人可以帮帮我吗?非常感谢你。

2 个答案:

答案 0 :(得分:5)

您需要在视图中添加POST条件,验证表单然后保存: https://docs.djangoproject.com/en/dev/topics/forms/#using-a-form-in-a-view

答案 1 :(得分:0)

如果您正在使用Django 1.5,请尝试THIS

也许您的观点可能是:

class RecadoFormView(FormView):
    model_class = RecadoForm
    template_name = 'recados/index.html'

    def valid_form(self, form):
        form.instance.save() # Or form.save()
        return super(RecadoFormView, self).valid_form(form)