我正在学习一些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))
和模板:
{% if lista_recados %} {% for recado in lista_recados %}{{ recado.nome }}
{{ recado.data }}
{{ recado.recado }}
{% endfor %} {% else %}Ainda não existem recados. Deixe o seu :)
{% endif %}
这会在页面上正确生成表单,但是当我单击提交按钮时,它不会将数据保存在数据库中,现在我无法弄清楚要做什么.用观点尝试了一些事情,但没有任何效果.
有谁可以帮助我吗?非常感谢你.
您需要在视图中添加POST条件,验证表单然后保存:https: //docs.djangoproject.com/en/dev/topics/forms/#using-a-form-in-a-view