表单提交而不是POST在Django中的值

编程入门 行业动态 更新时间:2024-10-24 23:20:44
本文介绍了表单提交而不是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,则阻止表单有效保存实例(参见 docs.djangoproject/zh-CN/1.5/topics/forms/modelforms/#the-save-method ).请记住,在Python中,每个对象都有一个布尔值...哎呀,您是说要 not 保存实例的形式;)

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 docs.djangoproject/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中的值

本文发布于:2023-10-09 18:38:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476465.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   而不是   Django   POST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!