[英]Save data of django form in database
I'm using Django 1.3 and I have a form defined with forms.py: 我正在使用Django 1.3,并且有一个用forms.py定义的表单:
class mopa(forms.Form):
idcarrellosorgente = forms.IntegerField(label="Identificativo Carrello Sorgente *", required=True, max_value=9999999999, min_value=0000000000 )
causale = forms.CharField(label="Causale Pagamento *", required=True)
imp_unitario = forms.DecimalField(label="Importo Unitario Bene (es. 20.00) *", required=True)
quantita_item = forms.IntegerField(label="Quantita' Bene Acquistato (intero) *", required=True)
and in this file I made the checks. 在这个文件中,我进行了检查。 My models.py file:
我的models.py文件:
class Mopamodel(models.Model):
idcarrellosorgente = models.IntegerField()
cod_ente = models.CharField()
causale = models.CharField()
imp_unitario = models.DecimalField()
quantita_item = models.IntegerField()
and my views.py 和我的views.py
def paga(request):
# If this is a POST request then process the Form data
if request.method == 'POST':
# Create a form instance and populate it with data from the request (binding):
form = mopa(request.POST)
print('form: ', form.data) #return a dictionary
# Check if the form is valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# p=form.save() <--don't works: error: 'mopa' object has no attribute 'save'
idcarr = form.cleaned_data['idcarrellosorgente']
caus = form.cleaned_data['causale']
imp_u = form.cleaned_data['imp_unitario']
qta = form.cleaned_data['quantita_item']
dictmopa={}
dictmopa['id_carr']=idcarr
cod_ente = form.cleaned_data['cod_ente']
mopapay=Mopamodel(idcarrellosorgente=idcarr, cod_ente=cod_ente, causale=causale, imp_unitario=imp_u, quantita_item=qta
#mopapay.save() <--this produce the error: unsupported operand type(s) for ** or pow(): 'Decimal' and 'NoneType'
....
# redirect to a new URL:
return HttpResponseRedirect(reverse('viewsdati/') )
How can I save the form data in a database postgres? 如何将表单数据保存在数据库Postgres中? Other tutorial/questions don't solve my problem, probably are for more recent django versions.
其他教程/问题不能解决我的问题,可能是针对较新的Django版本。
Well, you should use ModelForm
in this case. 好吧,在这种情况下,您应该使用
ModelForm
。 Change forms like this: 更改如下形式:
class mopa(forms.ModelForm):
class Meta:
model = Mopamodel
fields = ('idcarrellosorgente ', 'causale', 'imp_unitario', 'quantita_item ', )
Then change view to something like this: 然后将视图更改为如下所示:
def paga(request):
if request.method == 'POST':
form = mopa(request.POST)
if form.is_valid():
posted = form.save(commit=False)
posted.cod_ente = form.cleaned_data['cod_ente']
posted.save()
return HttpResponseRedirect(reverse('viewsdati/'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.