Reputation: 403
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 ?
Model file
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 uses the modelform
from contact.models import Contact
from django.forms import ModelForm
class AddcntForm(ModelForm):
class Meta:
model = Contact
Views
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))
Url
from django.conf.urls import *
from django.conf import settings
urlpatterns = patterns('contact.views',
url(r'^addcnt/$', 'add_cnt', name='add_cnt'),
)
template file is as follows
{% block content %}
<form method="post" action="/hr/addcnt/" >{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Ok" />
</form>
{% endblock %}
Upvotes: 2
Views: 5833
Reputation: 1
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.
Upvotes: 0
Reputation: 77902
You're passing the request.GET
querydict to your form when the method is POST
. You should pass request.POST
instead.
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 ;)
Upvotes: 2