表单提交而不是POST在Django中的值 [英] Form submit not POST's the value in Django

查看:67
本文介绍了表单提交而不是POST在Django中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我只是尝试使用这种简单的形式保存数据时,它没有被发布.在声明动作或网址时有什么问题吗?

When i just tried to save data using this simple form , it is not getting posted . Is there anything wrong in declaration of actions or url's ?

模型文件

   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使用模型形式

Form.py uses the modelform

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 %}

推荐答案

当方法为 POST 时,您会将 request.GET querydict传递给表单.您应该改为传递 request.POST .

You're passing the request.GET querydict to your form when the method is POST. You should pass request.POST instead.

您还将请求传递给 form.save(). ModelForm.save()所需的唯一(可选)参数是布尔值"commit"标志,如果为true,则阻止表单有效保存实例(参见

Also you're passing the request to form.save(). The only (optional) argument expected by ModelForm.save() is a boolean "commit" flag which, if true, prevent the form from effectively saving the instance (cf https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/#the-save-method). Remember that in Python each object have a boolean value... IOW you're saying the form to not save your instance ;)

这篇关于表单提交而不是POST在Django中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆