虽然标题说问题是“健康”。事实上,它在表格上挑选一个随机项目并说明问题。
surveys.views.py
from django.shortcuts import render
from surveys.forms import SurveyForm
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required
def storeBloodData(request):
if request.method == 'POST':
form = SurveyForm(request.POST)
if(form.is_valid()):
cd = form.cleaned_data
bd = SurveyForm (user=cd['user'],
timestamp=cd['timestamp'],
glucose=cd['glucose'],
wellness=cd['wellness'],
weight=cd['weight'],
foodGroups=cd['foodGroups'],
)
bd.save()
print("Saved weather record...")
else:
return render(request,
'bdata_form.html',{'form':form})
print("should be calling status...")
return render(request, 'welcome.html',{'term':"Saved data to d/base..."})
surveys.forms.py
from django import forms
from surveys.models import Survey
from django.conf import settings
FOOD_CHOICE = {
('D','Diary'),
('F','Fruit'),
('G','Grains'),
('M','Meats'),
('V','Vegetables'),
('S','Sweets'),
}
class SurveyForm(forms.ModelForm):
class Meta:
model = Survey
fields = ( 'glucose',
'weight', 'foodGroups',
'wellness', 'user',
'timestamp'
)
surveys.models.py
from django.db import models
from userprofile.models import UserProfile
from django.conf import settings
from django.contrib.auth.models import User
# Create your models here.
FOOD_CHOICE = {
('D','Diary'),
('F','Fruit'),
('G','Grains'),
('M','Meats'),
('V','Vegetables'),
('S','Sweets'),
}
NUM_CHOICE = {
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('5','5'),
('6','6'),
('7','7'),
('8','8'),
('9','9'),
('10','10'),
}
class Survey(models.Model):
user = models.ForeignKey(User, related_name='Survey.user')
glucose = models.DecimalField(max_digits=3, decimal_places=0)
timestamp = models.DateTimeField('date published', default='1990-08-26')
weight = models.DecimalField(max_digits=5, decimal_places=2)
foodGroups = models.CharField(max_length=1)
wellness = models.CharField(max_length=2, choices=NUM_CHOICE, default="1")
def __str__(self):
return self.user
更多信息 所以它正确地加载了表单(并且我能够从管理员端添加调查)但是每当我尝试从站点端添加它时,它都会抛出错误。
答案 0 :(得分:2)
您正尝试在is_valid块中实例化SurveyForm,而不是Survey。
但实际上你不应该尝试这两种方法,而且你不需要在cleaning_data中设置所有这些字段:使用ModelForm的全部意义在于你可以只做form.save()
并创建它并为您保存模型实例。