我正在使用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)
在这个文件中我做了检查。 我的models.py文件:
class Mopamodel(models.Model):
idcarrellosorgente = models.IntegerField()
cod_ente = models.CharField()
causale = models.CharField()
imp_unitario = models.DecimalField()
quantita_item = models.IntegerField()
和我的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/') )
如何将表单数据保存在数据库postgres中? 其他教程/问题无法解决我的问题,可能是针对更新的django版本。
答案 0 :(得分:0)
嗯,在这种情况下你应该使用ModelForm
。改变这样的形式:
class mopa(forms.ModelForm):
class Meta:
model = Mopamodel
fields = ('idcarrellosorgente ', 'causale', 'imp_unitario', 'quantita_item ', )
然后将视图更改为以下内容:
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/'))