当我只是尝试使用这个简单的表单保存数据时,它没有被发布。行动声明或网址有什么问题吗?
这里 request.method 是 GET 而不是 POST - 尽管表单方法设置为 POST
模型文件
from django.db import models
# Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=30, null=True, blank=True)
company_id = models.CharField(max_length=30)
def __unicode__(self):
return self.name
Form.py 使用模型表单
from contact.models import Contact
from django.forms import ModelForm
class AddcntForm(ModelForm):
class Meta:
model = Contact
意见
from contact.forms import AddcntForm
from django.contrib import messages
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template.context import RequestContext
def add_cnt(request, form_class=AddcntForm):
print request.method
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
form.save(request)
messages.success(request, "New Contact added.")
return redirect('##success##')
else:
form = form_class()
return render_to_response(
'vec/add_cnt.html',
{'form': form},
context_instance=RequestContext(request))
网址
from django.conf.urls import *
from django.conf import settings
urlpatterns = patterns('contact.views',
url(r'^addcnt/$', 'add_cnt', name='add_cnt'),
)
模板文件如下
{% block content %}
<form method="post" action="/hr/addcnt/" >{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Ok" />
</form>
{% endblock %}