2

当我只是尝试使用这个简单的表单保存数据时,它没有被发布。行动声明或网址有什么问题吗?

这里 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 %}
4

2 回答 2

2

request.GET方法为POST. 你应该通过request.POST

此外,您将请求传递给form.save(). 期望的唯一(可选)参数ModelForm.save()是布尔“提交”标志,如果为真,则阻止表单有效保存实例(参见https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/ #the-save-method)。请记住,在 Python 中,每个对象都有一个布尔值...... IOW 你说的是保存实例的表单;)

于 2013-10-21T11:23:22.333 回答
0

I was confused too with the same issue.

When the form is called initially it is "GET" request so the statement -print request.method will print "GET".

After entering values in the form if you click on submit, you can see in the console the same statement -print request.method will print "POST" which is actually a post request.

于 2020-10-18T19:50:02.207 回答