I try to apply the django poll application to my own application (an IMC calculator) to improve and build a little project for my first step in python/django.
I try to save the data of my first form that is on accueil.html:
<form action="" method="post">
<table>
{{ form.as_table }}
</table>
<input type ="submit" value="Submit">
</form>
Here is my forms.py:
from django import forms
class IndividuDataForm(forms.Form):
nom = forms.CharField(max_length=100)
prenom = forms.CharField(max_length= 100)
anniversaire = forms.DateField()
taille = forms.IntegerField()
poids = forms.IntegerField()
Here is my models.py:
from django.db import models
from django.forms import ModelForm
class Individu(models.Model):
nom = models.CharField(max_length=100)
prenom = models.CharField(max_length= 100)
anniversaire = models.DateField()
taille = models.IntegerField()
poids = models.IntegerField()
def __unicode__(self):
return self.nom
class ImcResultat(models.Model):
individu = models.ManyToManyField(Individu)
imc = models.IntegerField()
date_imc = models.DateField()
class IndividuForm(ModelForm):
class Meta:
model = Individu
class ImcResultatForm(ModelForm):
class Meta:
model = ImcResultat
And finally my *views.py* is here: the problem is at the line 13 * a = cd.create() * when I try to save the data from the form to the database.
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from models import Individu, ImcResultat
from forms import IndividuDataForm
def accueil(request):
if request.method == 'POST':
form = IndividuDataForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
a = cd.create() **#this is the problem**
return HttpResponseRedirect('/accueil/page2/')
else:
form = IndividuDataForm()
return render_to_response('accueil.html', {'form':form})
def page2(request):
return render_to_response('page2.html')
i guess it is on the first part of the views.py that my function do not work well, it does not save the form in the database. def accueil(request):
if request.method == 'POST':
form = IndividuDataForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
a = cd.create() **#this is the problem**
return HttpResponseRedirect('/accueil/page2/')
after checking if the form is valid, I clean the data in the form then try to save it. and I got this error:
Exception Type: AttributeError
Exception Value: 'dict' object has no attribute 'create'
I guess it is from a dictionnary but never in my code i use { } for dictionnary list. So I have no idea and stuck in the process of learning.
Thanks for your help and I hope from my first stackoverflow post I didn't made too many mistakes.
You should use a ModelForm, which will define the fields automatically to match those on the model. Then you can call form.save() to create the instance directly from the form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With